I have the following simple Aspect.
package com.example.foo.aspects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class TimingProfiler
{
private static final Log logger = LogFactory.getLog(TimingProfiler.class);
#Pointcut("execution(String *.toString())"
+ " || execution(int *.hashCode())"
+ " || execution(boolean *.equals(Object))"
+ " || execution(int *.getId())"
+ " || execution(String *.getName())")
public void whatIDontWantToMatch(){}
#Pointcut("execution(public * com.example.foo..*(..))")
public void whatIWantToMatch(){}
#Pointcut("whatIWantToMatch() && ! whatIDontWantToMatch()")
public void allIWantToMatch(){}
#Around("allIWantToMatch()")
public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable
{
Signature signature = joinPoint.getStaticPart().getSignature();
logger.info("Entering method " + signature);
Object returnValue = joinPoint.proceed();
logger.info("Leaving method " + signature);
return returnValue;
}
}
I get the following message during compilation, however.
[INFO] Join point 'method-execution(com.example.foo.bar.baz.snack.SnackIdentifier com.example.foo.bar.baz.snack.Snack.getId())' in Type 'com.example.foo.bar.baz.snack.Snack' (Snack.java:78) advised by around advice from 'com.example.foo.aspects.TimingProfiler' (foo-profiler-lib.jar!TimingProfiler.class(from TimingProfiler.java))
And when I run the code I get log messages from the methods I am trying to exclude.
How do I correctly include all of the public methods found in the com.example.foo package while excluding some specific ones?
I was overlooking the fact that my PointCut was excluding int getId() and the methods I was seeing show up in the output were SnackIdentifier getId(). The correct answer to this question is to pay attention.
Related
When I try to run the simplest PortableRunner pipeline on Java, I get the error:
Exception in thread "main" java.lang.RuntimeException: The Runner experienced the following error during execution:
java.io.IOException: error=2, No such file or directory
at org.apache.beam.runners.portability.JobServicePipelineResult.propagateErrors(JobServicePipelineResult.java:176)
at org.apache.beam.runners.portability.JobServicePipelineResult.waitUntilFinish(JobServicePipelineResult.java:117)
at org.apache.beam.examples.PythonExternal.runWordCount(PythonExternal.java:74)
at org.apache.beam.examples.PythonExternal.main(PythonExternal.java:81)
However, I do not read any files anywhere in the pipeline or I do not sink to anywhere. My arguments are
--runner=PortableRunner --jobEndpoint=localhost:8099
and code
package org.apache.beam.examples;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.options.*;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.Row;
import java.util.Arrays;
import java.util.List;
public class Simplest {
public static final Schema SCHEMA =
Schema.of(
Schema.Field.of("sentence", Schema.FieldType.STRING),
Schema.Field.of("count", Schema.FieldType.INT32));
public interface WordCountOptions extends PipelineOptions {
/** Set this option to specify Python expansion service URL. */
#Description("URL of Python expansion service")
String getExpansionService();
void setExpansionService(String value);
}
static void runWordCount(WordCountOptions options){
final List<String> LINES = Arrays.asList(
"To be, or not to be: that is the question: ",
"Whether 'tis nobler in the mind to suffer ",
"The slings and arrows of outrageous fortune, ",
"Or to take arms against a sea of troubles, ");
Pipeline p = Pipeline.create(options);
p.apply("ReadLines", Create.of(LINES)).setCoder(StringUtf8Coder.of())
.apply(ParDo
.of(new DoFn<String, Row>() {
#ProcessElement
public void processElement(#Element String element, OutputReceiver<Row> out, ProcessContext c) {
// In our DoFn, access the side input.
out.output(Row.withSchema(SCHEMA)
.withFieldValue("sentence", element)
.withFieldValue("count", 1)
.build());
}
}))
.setRowSchema(SCHEMA);
p.run().waitUntilFinish();
}
public static void main(String[] args) {
WordCountOptions options =
PipelineOptionsFactory.fromArgs(args).withValidation().as(WordCountOptions.class);
runWordCount(options);
}
}
Although the manual suggests adding --environment_type=LOOPBACK, I also get error as
Class interface org.apache.beam.examples.PythonExternal$WordCountOptions missing a property named 'environment_type'.
Beam Version: 2.40.0
I started the JobService endpoint docker run --net=host apache/beam_flink1.14_job_server:latest as suggested.
Any suggestions?
// Class CompteRepository
import org.springframework.data.jpa.repository.JpaRepository;
import org.entities.Compte;
public interface CompteRepository extends JpaRepository<Compte, String>{}
// CLASS BanqueMetierImpl``
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service // SPring couche Metier
#Transactional
public class BanqueMetierImpl implements IBanqueMetier{
#Autowired
private CompteRepository compteRepository;
#Override
public Compte consulterCompte(String code) {
Compte cp = compteRepository.findOne(code);
return cp;
}
// The method findOne show up this error The method findOne(Example) in //the type QueryByExampleExecutor is not applicable for the arguments //(String)
I think the method findOne() is unsupported by version 1.5.1.SNAPSHOT of SPRING BOOT , so in 2.0.1.SNAPSHOT it's replaced by FindById() which is a QueryByExampleExecutor it's an Optional method (see Optional in JAVA 8) so I resolved the problem like this:
#Override public Compte consulterCompte(String code) throws NotFoundException {
Optional<Compte> cp = compteRepository.findById(code);
return cp.orElseThrow(
() -> new NotFoundException("Unable to get Account with Code = " + code)
);
}
, i have a #Test method with dataprovider , i have a Listener.class , my target is that when my #Test method is success, the status of case in testrail is setted as "Passed" automatically in onTestSuccess Method of Listener class , this process is ok, but when i use dataprovider for #Test Method, this causes the problem
i want that same method must be worked (let say) three times because of dataprovider and different case id data must be sent to onTestSuccess method for each iteration from #Test method
My Listener.class
package com.myproject.test.listeners;
import java.lang.reflect.Method;
import org.testng.IClass;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class Listener implements ITestListener, ISuiteListener, IInvokedMethodListener {
...
public void onTestStart(ITestResult result) {
}
public void onTestSuccess(ITestResult result) {
try {
Program pr = new Program();
System.out.println("onTestSuccess Method for :" + result.getName());
String TestID = null;
String TestRunID = null;
for (Method testMethod : result.getTestClass().getRealClass().getMethods()) {
if (testMethod.getName().equals(result.getName()) && testMethod.isAnnotationPresent(UseAsTestRailId.class)) {
UseAsTestRailId useAsTestName = testMethod.getAnnotation(UseAsTestRailId.class);
TestID = Integer.toString(useAsTestName.testRailCaseId());
TestRunID = Integer.toString(useAsTestName.testRailRunId());
System.out.println("Case ID---> " + TestID + " Run ID--> " + TestRunID);
// 1 = Passed
pr.enterTestResult(TestRunID, TestID, 1);
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
...
}
My test class (SettingsTests.java) including my #Test method (checkCurrentPasswordFormatIsValidatedTest)
#Listeners(com.test.listeners.Listener.class)
//listener annotation row is written in BaseTest class
public class SettingsTests extends BaseTest {
...
/**
* Test Case - C5001275 - Check that "Please enter at least 8 characters."
* message is displayed when entered value into "Current Password" field in
* wrong format This case will run two times!
*
* #param currentPasswordValue
*/
#Test(dataProvider = "currentPasswordTestWithWrongValue")
#UseAsTestRailId(testRailCaseId = 5001275,testRailRunId = 56662)
// aim is that to send different case id for each iteration,now even if method works twice , only one testRailCaseId is sent
public void checkCurrentPasswordFormatIsValidatedTest(String currentPasswordValue) {
logger.trace("STARTING TEST: checkCurrentPasswordFormatisValidatedTest");
logger.trace("Test Step : Enter current password in wrong format");
settingsPageObject.enterCurrentPassword(currentPasswordValue);
logger.trace("Test Step : Click on the button 'UPDATE' ");
settingsPageObject.clickOnUpdateButton();
logger.trace("Expected Result: The message 'Please enter at least 8 characters.' is displayed on screen.");
Assert.assertEquals(settingsPageObject.getCurrentPasswordWrongText(), "Please enter at least 8 characters.");
}
#DataProvider(name = "currentPasswordTestWithWrongValue")
public static Object[][] validateTestWithCurrentPasswordInWrongFormat() {
return new Object[][] { { RandomStringUtils.randomAlphabetic(7) }, { RandomStringUtils.randomAlphabetic(1) } };
}
...
}
My annotation class (UseAsTestRailId.java)
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface UseAsTestRailId
{
int testRailCaseId() default 0;
int testRailRunId() default 0;
String[] tags() default "";
}
Some #Test methods to set two case status, some #Test methods to set three case status in testRail,so the more dataprovider data set needed the more case id needed , it must be dynamical
You can use the setattribute value in the testresult object to set custom value. Get the currentresult from Reporter : Reporter.getCurrentTestresult and then setAttribute ("TC_id",sasdf) and use that in your ontestsuccess using the getAttribute ("TC_id") on result object.
Could you please help me to solve my problem with GWT Generator? Let me explain.
I wish to generate a widget (ListBox with pre-defined values) during the compilation time and I use GWT Generator for that. My solution works as expected in DevMode (when I run the project with mvn gwt:run) and I see the generated listbox on the screen. But when I compile the code and run it in the "Production mode" (using command mvn clean gwt:compile jetty:run-war) I see the dumb listbox with only one item "no-value" instead.
I have one idea about the issue reason. I use GIN in my project. Despite the fact, that I substitute my empty listbox with generated one using Deferred Binding but not GIN Injection, it probably somehow prevents the substitution during the runtime. I tried my listbox on an empty testing project - everything worked as desired in both Dev Mode and Production Mode. But it fails on my working project.
Here is my realisation:
package com.test.generated;
import com.google.gwt.user.client.ui.IsWidget;
public interface IMySelectBox extends IsWidget {}
My empty selectbox:
package com.test.generated;
import com.google.gwt.user.client.ui.ListBox;
/**
* <p>Dumb listbox. It should be replaced with generated file.</p>
*
*/
public class MySelectBox implements IMySelectBox {
#Override
public ListBox asWidget() {
ListBox listBox = new ListBox();
listBox.addItem("no-value","no-value");
return listBox;
}
}
My Generator:
package com.test.generated;
import java.io.PrintWriter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
/**
* Generates the ListBox and populates it
*
*/
public class SelectBoxGenerator extends Generator {
/**
* {#inheritDoc}
*/
#Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
JClassType classType = context.getTypeOracle().getType(typeName);
return this.getSourceWriter(classType, context, logger);
} catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* Generates the source code of the List box.
*/
private String getSourceWriter(JClassType classType, GeneratorContext context, TreeLogger logger) {
final String packageName = classType.getPackage().getName();
final String className = classType.getSimpleSourceName() + "GeneratedImpl";
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter == null) {
// source code has already been generated, abort
return null;
}
ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
// Extends
composer.setSuperclass(classType.getName());
// Implements interface IMySelectBox
composer.addImplementedInterface(IMySelectBox.class.getSimpleName());
// Imports
composer.addImport(ListBox.class.getName());
// Class body
SourceWriter src = composer.createSourceWriter(context, printWriter);
src.println("#Override");
src.println("public ListBox asWidget() {");
src.println("ListBox sb = new ListBox();");
// ...here I generate values for the selectbox during compilation time.
src.println("return sb;");
src.println("}");
src.commit(logger);
System.out.println("Generating for: " + className);
// return the fully qualifed name of the generated class
return packageName + "." + className;
}
}
This is how I declare the substitution in my module.gwt.xml file:
<generate-with class="com.test.generated.SelectBoxGenerator">
<when-type-assignable class="com.test.generated.IMySelectBox" />
</generate-with>
And I use my generated ListBox as usually:
IMySelectBox mySelectBox = GWT.create(MySelectBox.class);
anyPanel.add(mySelectBox);
As you can see, I don't touch GIN stuff here at all. I use GIN to inject my modules and views. I found Issue 95 in GIN website, probably it is related to my case.
I will be really glad to get any help. Any explanations, hints, workarounds, suggestions are welcome!
Thank you very much in advance!
I try to make a cordova plugin in IBM worklight.
Javascript:
HelloWorld = {
sayHello: function (success, fail, resultType) {
Cordova.exec(
success,
fail,
"HelloWorld",
"HelloWorld",
[resultType]
);
}
};
function callFunction() {
HelloWorld.sayHello(basarili, basarisiz, "sinan");
}
Java:
package com.Cordova1;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import android.util.Log;
public class HelloWorld extends CordovaPlugin {
public boolean execute(String arg0, JSONArray arg1, String arg2) {
Log.d("HelloPlugin", "Hello, this is a native function called from PhoneGap/Cordova!");
return true;
}
}
When I call callFunction I see that fail function worked. Also, I can't see any HelloPlugin message in log window.
What can I do ?
module 09_3 ApacheCordovaPlugin in the samples is indeed using the deprecated Plugin class instead of CordovaPlugin. I have rewritten the HelloWorldPlugin class in module 09_3 to eliminate the deprecated Cordova Plugin API usage. The sample is working fine.
package com.AndroidApacheCordovaPlugin;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
public class HelloWorldPlugin extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray arguments,
CallbackContext callbackContext) throws JSONException {
if (action.equals("sayHello")) {
String responseText = "Hello world";
try {
responseText += ", " + arguments.getString(0);
callbackContext.success(responseText);
return true;
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
} else {
callbackContext.error("Invalid action: " + action);
return false;
}
return false;
}
}
A couple of things, 1) did you add a line for your plugin into the config.xml file? and 2) you seem to be overriding the wrong method in CordovaPlugin. It should be:
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
I was having the same problem. Have a look at module 09_3 ApacheCordovaPlugin in the samples. That example does work for me, but they are using the deprecated Plugin class instead of CordovaPlugin.
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
...
public class HelloWorldPlugin extends Plugin {
public PluginResult execute(String action, JSONArray arguments, String callbackId) {
The deprecated class returns PluginResult, not a boolean. I've tried the same code using the CordovaPlugin signature and that results in a fail every time. Apparently whatever WL code is invoking the plugin is apparently expecting the signature of the deprecated class.
I solved the problem.
I use the version 2.4 of cordova. I can't understand why it didn't work. when I use "cordova.exec" it doesn't work, however when I use PhoneGap.exec it works.
Also I looked for the definition;
In the last line of cordova-2.4.0.js, it says
var PhoneGap = cordova;
Ok, Phonegap was defined, but I don't know why cordova doesn't work.
Thank you for your answers.