secuesocial 3.0-M1 on play2.1.0? - java

I've been using play 2.1.0 for a while and I've been having trouble looking for a way to get securesocial to work. I tried different versions, even downloaded the latest typesafe activator to try to use it with play2.4 but no luck.
Does anyone know if can I use securesocial 3.0-M1 with play 2.1.0?
my controllers\application.java
package controllers;
import play.Logger;
import play.libs.F;
import play.mvc.Controller;
import play.mvc.Result;
import securesocial.core.BasicProfile;
import securesocial.core.RuntimeEnvironment;
import securesocial.core.java.SecureSocial;
import securesocial.core.java.SecuredAction;
import securesocial.core.java.UserAwareAction;w
import service.DemoUser;
import views.html.index;
import views.html.linkResult;
public class Application extends Controller {
public static Logger.ALogger logger =
Logger.of("application.controllers.Application");
private RuntimeEnvironment env;
public Application(RuntimeEnvironment env) {
this.env = env;
}
public Result index() {
if(logger.isDebugEnabled()){
logger.debug("access granted to index
DemoUser user = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
return ok(index.render(user, SecureSocial.<DemoUser>env()));
}
#UserAwareAction
public Result userAware()
{
DemoUser demoUser = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
String userName ;
if ( demoUser != null ) {
BasicProfile user = demoUser.main;
if ( user.firstName().isDefined() ) {
userName = user.firstName().get();
} else if ( user.fullName().isDefined()) {
userName = user.fullName().get();
} else {
userName = "authenticated user";
}
} else {
userName = "guest";
}
return ok("Hello " + userName + ", you are seeing a public page");
}
#SecuredAction(authorization = WithProvider.class, params = {"twitter"})
public Result onlyTwitter() {
return ok("You are seeing this because you logged in using Twitter");
}
#SecuredAction
public Result linkResult() {
DemoUser current = (DemoUser) ctx().args.get(SecureSocial.USER_KEY
}
public F.Promise currentUser() {
return SecureSocial.currentUser(env).map( new F.Function<Object, Result>() {
#Override
public Result apply(Object maybeUser) throws Throwable {
String id;
if ( maybeUser != null ) {
DemoUser user = (DemoUser) maybeUser;
id = user.main.userId();
} else {
id = "not available. Please log in.";
}
return ok("your id is " + id);
}
});
}
}
my routes
Home page
GET / #controllers.Application.index
GET /userAware #controllers.Application.userAware
GET /only-twitter #controllers.Application.onlyTwitter
GET /link-result #controllers.Application.linkResult
GET /current-user #controllers.Application.currentUser
GET /assets/*file controllers.Assets.at(path="/public", file)
-> /auth securesocial.Routes
my error
[info] Set current project to playMongoDemooo (in build file:/C:/Users/kayjee%20
lahong/demo2/)
[info] Updating {file:/C:/Users/kayjee%20lahong/demo2/}playMongoDemooo...
[info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)
[info] Compiling 6 Scala sources and 6 Java sources to C:\Users\kayjee lahong\de
mo2\target\scala-2.10\classes...
[error] C:\Users\kayjee lahong\demo2\conf\routes:10: Cannot use a method returni
ng play.libs.F.Promise[play.mvc.Result] as an Handler
[error] GET /current-user #controllers.Application.currentUser
[error] C:\Users\kayjee lahong\demo2\conf\routes:10: Cannot use a method returni
ng play.libs.F.Promise[play.mvc.Result] as an Handler
[error] GET /current-user #controllers.Application.currentUser
[error] two errors found
[error] (compile:compile) Compilation failed
[error] application -
thank you

For Play 2.4 compatibility use 3.0-M4 or newer. The version you were trying to use does not work with 2.4.

Related

How to use an Event Hub Trigger in a Java Azure Function

I am attempting to create a Java Azure Function that triggers off of an Azure Event Hub. I am following these code snippets: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs-trigger?tabs=java#example
Here is my code:
package com.function;
import com.microsoft.azure.functions.*;
import com.microsoft.azure.function.annotation.*;
import java.util.Optional;
public class function {
#FunctionName("MTI")
public void EventHubProcess(
#EventHubTrigger(name = "msg", eventHubName = "mticallhub", connection = "EHubConnectionString"), String message, final ExecutionContext context)
{
context.getLogger().info("Java HTTP trigger processed a request: " + message);
}
}
Here is the error I get when building:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project func-MTI-test-zyg-001: Compilation failure
[ERROR] /C:/JavaStuff/FunctionApps/func-MTI-test-zyg-001/src/main/java/com/function/Function.java:[34,105] illegal start of type
Here is the error popup in VSCode:
I've been looking for hours and exhausted page after page of Google searches. What am I doing wrong?
Please change
#EventHubTrigger(name = "msg", eventHubName = "mticallhub", connection = "EHubConnectionString"), String message, final ExecutionContext context)
to
#EventHubTrigger(name = "msg", eventHubName = "mticallhub", connection = "EHubConnectionString") String message, final ExecutionContext context)

How to read Jenkins credentials at Folder level

I am trying to migrate credentials from Jenkins to another credentials store.
I want to read the credentials from the Jenkins store, and have found this script (https://github.com/tkrzeminski/jenkins-groovy-scripts/blob/master/show-all-credentials.groovy
The script does the job OK for SystemCredentialsProvider credentials for the global domain at root level.
But my credentials are stored in a Folder, so the script does not work for me.
I am using the Jenkins script console to execute the script.
If I navigate to the Jenkins Credentials configuration page and hover over the icon for one of my credential entries, the tooltip says "Folder Credentials Provider".
====================================================
Question: How do I read all of the the credentials from a Folder in Jenkins?
====================================================
Please see script, below:
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
def showRow = { credentialType, secretId, username = null, password = null, description = null ->
println("${credentialType} : ".padLeft(20) + secretId?.padRight(38)+" | " +username?.padRight(20)+" | " +password?.padRight(40) + " | " +description)
}
// set Credentials domain name (null means is it global)
domainName = null
credentialsStore = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0]?.getStore()
domain = new Domain(domainName, null, Collections.<DomainSpecification>emptyList())
credentialsStore?.getCredentials(domain).each{
if(it instanceof UsernamePasswordCredentialsImpl)
showRow("user/password", it.id, it.username, it.password?.getPlainText(), it.description)
else if(it instanceof BasicSSHUserPrivateKey)
showRow("ssh priv key", it.id, it.passphrase?.getPlainText(), it.privateKeySource?.getPrivateKey(), it.description)
else if(it instanceof AWSCredentialsImpl)
showRow("aws", it.id, it.accessKey, it.secretKey?.getPlainText(), it.description)
else if(it instanceof StringCredentials)
showRow("secret text", it.id, it.secret?.getPlainText(), '', it.description)
else if(it instanceof FileCredentialsImpl)
showRow("secret file", it.id, it.content?.text, '', it.description)
else
showRow("something else", it.id, '', '', '')
}
return
i simply created a Java class to retrieve the credentials from either global or folder scope:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.hudson.plugins.folder.Folder
class JenkinsCredentials
{
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userName, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the username is searched for first in the global jenkins level, and if not found then it is searched at the folder level
*/
public static StandardUsernamePasswordCredentials getCredentialsByUsername(String userName, String fromFolder) throws Exception
{
List credsList = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, Jenkins.getInstance());
if(credsList == null || credsList.size() == 0)
{
credsList = getFolderLevelCredentialsList(fromFolder);
}
return credsList.findResult { it.username == userName ? it : null };
}
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userID, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the userID is searched for first in the global jenkins level, and if not found then it is searched at the folder level
*/
public static StandardUsernamePasswordCredentials getCredentialsByID(String userID, String fromFolder) throws Exception
{
List credsList = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, Jenkins.getInstance());
if(credsList == null || credsList.size() == 0)
{
credsList = getFolderLevelCredentialsList(fromFolder);
}
return credsList.findResult { it.id == userID ? it : null };
}
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userName, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the username is searched for at the folder level who's name we provided as 'fromFolder'
*/
public static StandardUsernamePasswordCredentials getFolderCredentialsByUsername(String userName, String fromFolder) throws Exception
{
List credsList = getFolderLevelCredentialsList(fromFolder);
return credsList.findResult { it.username == userName ? it : null };
}
/**
* this method gets a 'StandardUsernamePasswordCredentials' for a userID, the 'StandardUsernamePasswordCredentials' object
* have 2 fields - user and password, which can be used to login to other systems,
* the userID is searched for at the folder level who's name we provided as 'fromFolder'
*/
public static StandardUsernamePasswordCredentials getFolderCredentialsByID(String userID, String fromFolder) throws Exception
{
List credsList = getFolderLevelCredentialsList(fromFolder);
return credsList.findResult { it.id == userID ? it : null };
}
/**
* this method gets a list of credentials set at a folder level, the method receives the folder name to get the credentials from
*/
public static List getFolderLevelCredentialsList(String folderName)
{
return CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, getFolderItem(folderName));
}
/**
* this method fetch a 'Folder' item from jenkins instance by a folder name
* it then can be used in the other methods to search for a user credentials at that folder level
*/
public static Folder getFolderItem(String folderName)
{
def allJenkinsItems = Jenkins.getInstance().getItems();
for (currentJenkinsItem in allJenkinsItems)
{
if(currentJenkinsItem instanceof Folder)
{
if(((Folder)currentJenkinsItem).getFullName().contains(folderName))
{
return (Folder)currentJenkinsItem;
}
}
}
}
}
then you can use it like this:
get credentials for userName 'shay bc' from folder named 'MyJenkinsFolder':
// get the credentials
StandardUsernamePasswordCredentials shaybcCredentials = JenkinsCredentials.getFolderCredentialsByUsername("shay bc", "MyJenkinsFolder")
// login to some system using the credentials
sshSession.login(shaybcCredentials.getUsername(), shaybcCredentials.getPassword())
get credentials for userID 'sbc' from folder named 'MyJenkinsFolder':
// get the credentials
StandardUsernamePasswordCredentials sbcCredentials = JenkinsCredentials.getFolderCredentialsByID("sbc", "MyJenkinsFolder")
// login to some system using the credentials
sshSession.login(sbcCredentials.getUsername(), sbcCredentials.getPassword())
The class shared by #Shaybc was most of the solution, and although a commenter suggested it was not a complete solution by itself, I was able to guess how to implement it correctly into such a complete solution in my own Groovy script.
The Folder returned by JenkinsCredentials.getFolderItem('foldername') is taking the same string slug as your folder is addressed by in Jenkins. So if you have a folder with a descriptive name, and a slug, like "Folder Name" and "foldername", the right string to use to retrieve the folder itself is "foldername".
The example provided here shows how to retrieve credentials from the global store, this is Jenkins.instance – for complete documentation the script they provide is copied here:
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
Jenkins.instance,
null,
null
);
for (creds in jenkinsCredentials) {
println(jenkinsCredentials.id)
}
So, start your script by defining class JenkinsCredentials as #Shaybc described, then instead of calling CredentialsProvider.lookupCredentials with Jenkins.instance, retrieve the folder and pass it in there instead.
My folder was called "ft" and (skipping over the import/boilerplate at the top and the definition of JenkinsCredentials helper class,) the remainder of my invocation in the Groovy script looked like:
def folder = JenkinsCredentials.getFolderItem('ft');
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
folder,
null,
null
);
for (c in creds) {
println(c.id + ": " + c.description)
}
Hope this helped someone! and by the way, if your credentials are stored in a file instead of a string, you have one more step... the file will not have any useful content in the "description" attribute, you need the byte stream stored at c.getContent()
So, that final loop with some metaprogramming to dynamically check for the availability of a getContent() method to call:
for (c in creds) {
if (c.metaClass.respondsTo(c, 'getContent')) {
println(
IOUtils.toString(c.getContent(), StandardCharsets.UTF_8)
)
}
println(c.id + ": " + c.description)
}
That last part was borrowed from this answer, which shows as well how you can import StandardCharsets and IOUtils: https://stackoverflow.com/a/42360792/661659
Just to add to this really awesome class from #Shaybc... If you're like me and have nested folders, you'll want to change up the Class method getFolderItem to recurse into all of the "sub-folders"... Otherwise you'll only ever get a return/hit on the top-level (root) Jenkins items.
Here's what that looks like, replacing the getFolderItem method and adding a getFolderItemRecursively method to do the work.
private static Folder getFolderItemRecursively(Folder folder, String folderName) {
for (nestedItem in folder.getItems()) {
if (nestedItem instanceof Folder) {
if(nestedItem.getFullName().contains(folderName)) {
return nestedItem;
} else {
def recurse = getFolderItemRecursively(nestedItem, folderName);
if (recurse instanceof Folder) {
return recurse;
}
}
}
}
}
public static Folder getFolderItem(String folderName)
{
for (item in Jenkins.getInstance().getItems())
{
if(item instanceof Folder)
{
if(item.getFullName().contains(folderName))
{
return item;
} else {
def recurse = getFolderItemRecursively(item, folderName);
if (recurse instanceof Folder) {
return recurse;
}
}
}
}
}
import jenkins.model.*
import hudson.model.ModelObject
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import com.cloudbees.hudson.plugins.folder.Folder
class DeepCredentialsPrinter {
private static final boolean DEBUG = false;
private final out;
private final Set<CredentialsStore> visitedStores = new HashSet<>();
DeepCredentialsPrinter(out) {
this.out = out;
}
private void start() {
process(Jenkins.getInstance())
}
private void process(ItemGroup group) {
printCreds(group);
List<ItemGroup> items = group.getItems();
if (items == null || items.isEmpty()) {
return;
}
for (item in items) {
if (item instanceof ItemGroup) {
process(item);
} else if (item instanceof Item) {
printCreds(item)
} else {
if (DEBUG) {
out.println("[DEBUG] unsupported item type: " + item.getClass().getCanonicalName());
}
}
}
}
private void printCreds(ModelObject model) {
for (store in CredentialsProvider.lookupStores(model)) {
if (visitedStores.add(store)) { // only visit new stores
print(model.getFullName(), store.getCredentials(Domain.global()));
}
}
}
private void print(String fullname, List<Credentials> creds) {
if (creds.isEmpty()) {
if (DEBUG) {
out.println("[DEBUG] No credentials in /" + fullname);
}
} else {
for (c in creds) {
out.println("Folder: /" + fullname)
out.println(" id: " + c.id)
if (c.properties.description) {
out.println(" description: " + c.description)
}
if (c.properties.username) {
out.println(" username: " + c.username)
}
if (c.properties.password) {
out.println(" password: " + c.password)
}
if (c.properties.passphrase) {
out.println(" passphrase: " + c.passphrase)
}
if (c.properties.secret) {
out.println(" secret: " + c.secret)
}
if (c.properties.secretBytes) {
out.println(" secretBytes: ")
out.println("\n" + new String(c.secretBytes.getPlainData()))
}
if (c.properties.privateKeySource) {
out.println(" privateKey: " + c.getPrivateKey())
}
if (c.properties.apiToken) {
out.println(" apiToken: " + c.apiToken)
}
if (c.properties.token) {
out.println(" token: " + c.token)
}
out.println("")
}
}
}
}
new DeepCredentialsPrinter(getBinding().out).start();
From all the above comments, Here is the code to list all the folder level credentials which prints all properties based on type of credential
Somewhat related to the original ask, I needed to do the inventory of all credentials stored in Jenkins. None of the answers so far have provided a solution that works out-of-the-box to dump all Jenkins credentials...
Based on the elements of answers provided by #TimWelch and #Kingdon, I wrote the following groovy (admin) script, which prints all credentials IDs and their type starting from the root folder to the deepest folders (recursive), while also avoiding printing duplicates:
import jenkins.model.*
import hudson.model.ModelObject
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import com.cloudbees.hudson.plugins.folder.Folder
class DeepCredentialsPrinter {
private static final boolean DEBUG = false;
private final out;
private final Set<CredentialsStore> visitedStores = new HashSet<>();
DeepCredentialsPrinter(out) {
this.out = out;
}
private void start() {
out.println("Folder,Credentials Type,Credentials ID") // header
process(Jenkins.getInstance())
}
private void process(ItemGroup group) {
printCreds(group);
List<ItemGroup> items = group.getItems();
if (items == null || items.isEmpty()) {
return;
}
for (item in items) {
if (item instanceof ItemGroup) {
process(item);
} else if (item instanceof Item) {
printCreds(item)
} else {
if (DEBUG) {
out.println("[DEBUG] unsupported item type: " + item.getClass().getCanonicalName());
}
}
}
}
private void printCreds(ModelObject model) {
for (store in CredentialsProvider.lookupStores(model)) {
if (visitedStores.add(store)) { // only visit new stores
print(model.getFullName(), store.getCredentials(Domain.global()));
}
}
}
private void print(String fullname, List<Credentials> creds) {
if (creds.isEmpty()) {
if (DEBUG) {
out.println("[DEBUG] No credentials in /" + fullname);
}
} else {
for (c in creds) {
out.printf("/%s,%s,%s\n", fullname, c.getClass().getSimpleName(), c.id)
}
}
}
}
new DeepCredentialsPrinter(getBinding().out).start();
gist: https://gist.github.com/fabienrenaud/349764873855533abc71b7fadafdf29e
The printCreds method can easily be extended to print more data for each secret type.

IONIC 3 : UnhandledPromiseRejectionWarning when generating APK File

I'm facing problems when generating apk file. I get the following error.
Command : ionic cordova build android
Output :
> cordova build android
Android Studio project detected
ANDROID_HOME=C:\Users\****\AppData\Local\Android\Sdk
JAVA_HOME=C:\Program Files\Java\jdk-9.0.4
(node:17504) UnhandledPromiseRejectionWarning: Unhandled promise rejection (reje
ction id: 1): CordovaError: Requirements check failed for JDK 1.8 or greater
(node:17504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
[13:47:49] lint finished in 8.47 s
This is the content of my rest file rest.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class RestProvider {
private baseUrl = 'http://localhost/project/web/rest/mobile/v1/';
private nomsvillesUrl = this.baseUrl + 'ville/nomsvilles/1';
constructor(public http: HttpClient) {
console.log('Hello RestProvider Provider');
}
getNomvilles(): Observable<string[]> {
return this.http.get(this.nomsvillesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res;
return body || { };
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const err = error || '';
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
This is the content of my main class main.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';
#Component({
selector: 'page-main',
templateUrl: 'main.html',
})
export class MainPage {
villes: string[]
errorMessage: string
constructor(public navCtrl: NavController, public navParams: NavParams, public rest: RestProvider) {
}
ionViewDidLoad() {
this.getVilles();
}
getVilles() {
this.rest.getNomvilles().subscribe(
villes => this.villes = villes,
error => this.errorMessage = <any>error
);
}
}
Please help me ! I want to know how to handle Promise in order to prevent promise rejection.
Thank you .
The error has nothing related to your code. It's asking for jdk 1.8 or higher you can download it from this link. But first uninstall jdk 1.9 you're using because it's not compatible with android.
Then create a environment variable JAVA_HOME=C:\path\to\jdk\bin

Discovering test with JUnit 5 doesn't execute LoggingListener (implementation of TestExecutionListeners)

I'm using JUnit Jupiter version 5.0.0 (Release version) and I'm trying to use the test discovery feature.
The documentation of Junit can be found in 7.1.1. Discovering Tests from http://junit.org/junit5/docs/5.0.0/user-guide/#launcher-api-discovery
My implementation is:
import static org.junit.platform.engine.discovery.ClassNameFilter.includeClassNamePatterns;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.LoggingListener;
public class MainPrueba {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
System.out.println("Runing thread INI");
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(
selectPackage("org.package.qabootfx.test.ping")
//,selectClass(QabootfxApplicationTests.class)
)
.filters(
//includeClassNamePatterns(".*Test")
includeClassNamePatterns(".*")
)
.build();
Launcher launcher = LauncherFactory.create();
TestPlan testPlan = launcher.discover(request);
for (TestIdentifier root : testPlan.getRoots()) {
System.out.println("Root: " + root.toString());
for (TestIdentifier test : testPlan.getChildren(root)) {
System.out.println("Found test: " + test.toString());
}
}
// Register a listener of your choice
//TestExecutionListener listener = new SummaryGeneratingListener();
TestExecutionListener listener = LoggingListener.forJavaUtilLogging(); //new LoggingListener();
launcher.registerTestExecutionListeners(listener);
launcher.execute(request);
System.out.println("Runing thread END");
};
new Thread(task).start();
Thread.sleep(5000);
System.out.println("END");
}
}
Examining LoggingListener class implementation we can see that this must print to the console the results. For example:
package org.junit.platform.launcher.listeners;
#API(status = MAINTAINED, since = "1.0")
public class LoggingListener implements TestExecutionListener {
....
#Override
public void testPlanExecutionStarted(TestPlan testPlan) {
log("TestPlan Execution Started: %s", testPlan);
}
#Override
public void testPlanExecutionFinished(TestPlan testPlan) {
log("TestPlan Execution Finished: %s", testPlan);
}
...
}
and my Test class is:
public class QabootfxApplicationTest {
#Test
public void testAbout() {
System.out.println("TEST Execution.... QabootfxApplicationTests.testAbout()");
assertEquals(4, 5, "The optional assertion message is now the last parameter.");
}
}
I'm expecting see in the console something similar to:
2017-09-20 10:53:48.041 INFO 11596 --- TestPlan Execution Started: ....
2017-09-20 10:53:48.041 INFO 11596 --- TestPlan Execution Finished: ....
but I can't see nothing similar to "... TestPlan Execution Started...".
The console output is:
Runing thread INI
Root: TestIdentifier [uniqueId = '[engine:junit-jupiter]', parentId = null, displayName = 'JUnit Jupiter', legacyReportingName = 'JUnit Jupiter', source = null, tags = [], type = CONTAINER]
Found test: TestIdentifier [uniqueId = '[engine:junit-jupiter]/[class:org.package.qabootfx.test.ping.QabootfxApplicationTest]', parentId = '[engine:junit-jupiter]', displayName = 'QabootfxApplicationTest', legacyReportingName = 'org.package.qabootfx.test.ping.QabootfxApplicationTest', source = ClassSource [className = 'org.package.qabootfx.test.ping.QabootfxApplicationTest', filePosition = null], tags = [], type = CONTAINER]
TEST Executon.... QabootfxApplicationTests.testAbout()
Runing thread END
END
Could be a bug? or I'm implementing something wrong?
Why would you expect the listener created by LoggingListener.forJavaUtilLogging() to log anything at log level INFO... when the documentation explicitly states the following?
Create a LoggingListener which delegates to a java.util.logging.Logger using a log level of FINE.
If you want the LoggingListener to log messages at level INFO, you'll have to create it using the other factory method which accepts a log level like this LoggingListener.forJavaUtilLogging(Level.INFO).

Why am I not seeing my Java / SalesForce / Google App?

I'm currently working on a SalesForce.com tutorial entitled Force.com for Google App Engine for Java: Getting Started
I've installed the Google Eclipse Plugin, downloaded the libraries, and entered the "Hello World App" (as seen on the tutorial page):
package com.force;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.*;
import java.util.logging.*;
import com.sforce.ws.*;
import com.sforce.soap.partner.*;
import com.sforce.soap.partner.sobject.SObject;
#SuppressWarnings("serial")
public class HelloWorldServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(HelloWorldServlet.class.getName());
private String username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private String password = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private PartnerConnection connection;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("Hello, world. this is a test2");
PrintWriter t = resp.getWriter();
getConnection( t, req);
if ( connection == null ) { return; }
QueryResult result = null;
try {
result = connection.query( "select id, name, phone from Account order by LastModifiedDate desc limit 10 ");
} catch (ConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (SObject account : result.getRecords()) {
t.println("<li>"+ (String)account.getField("Name") + "</li>");
}
}
void getConnection(PrintWriter out, HttpServletRequest req) {
try {
// build up a ConnectorConfig from a sid
String sessionid = req.getParameter("sid");
String serverurl = req.getParameter("srv");
if ( connection == null ) {
out.println("<p>new connection needed</p>");
// login to the Force.com Platform
ConnectorConfig config = new ConnectorConfig();
if ( sessionid != null && serverurl != null) {
config.setServiceEndpoint(serverurl);
config.setSessionId(sessionid);
config.setManualLogin(false);
out.println("using session from query string");
} else {
config.setUsername(username);
config.setPassword(password);
}
connection = Connector.newConnection(config);
out.println( connection.getConfig().getSessionId() );
out.println( connection.getConfig().getServiceEndpoint() );
} else {
out.println("<p> reuse existing connection");
out.println( connection.getConfig().getSessionId() );
}
log.warning("Connection SID " +connection.getConfig().getSessionId());
} catch ( ConnectionException ce) {
log.warning("ConnectionException " +ce.getMessage());
out.println( ce.getMessage() + " s " + ce.getClass() );
}
}
}
When I run the application as a "Web Application" I get the following in the console:
Initializing AppEngine server
Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
Successfully processed D:\education\java\HelloWorldOriginal\war\WEB-INF/appengine-web.xml
Successfully processed D:\education\java\HelloWorldOriginal\war\WEB-INF/web.xml
The server is running at http://localhost:8888/
Warning: default mime table not found: C:\devtool\Java\jre6\lib\content-types.properties
When I try to visit http://localhost:8080/ , I see:
Oops! Google Chrome could not connect to localhost:8080
Did you mean: localhost-­8080.­com
Additional suggestions:
Try reloading: localhost:­8080
Search on Google:
Google Chrome Help - Why am I seeing this page?
©2011 Google - Google Home
But when I visit http://localhost:8888/ , I get:
Web Application Starter Project
Please enter your name:
Send
(Which, also isn't the desired or expected outcome.)
What is this content-type.properties that I'm missing and how can I fix it? Or is that just a symptom of a greater problem?
Have you checked that your web.xml directs requests for / to the appropriate handler class? Just writing the class isn't enough - you have to make sure that incoming requests are directed to it.

Categories

Resources