I am using Spring AOP for logging wherein I want to log input/output of all methods present in package. I have written following pointcut for target package.
#Pointcut("within(com.mypackage.model.*)")
public void allmethods(){};
My logging method is as below.
#Before("allmethods()")
public void LoggingAdviceBefore(JoinPoint joinPoint)
{
StringBuffer logMessage = new StringBuffer();
if(joinPoint != null && joinPoint.getTarget()!=null && joinPoint.getTarget().getClass()!=null)
{
logMessage.append(joinPoint.getTarget().getClass().getName());
logMessage.append(".");
logMessage.append(joinPoint.getSignature().getName());
logMessage.append("(");
// append args
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
logMessage.append(args[i]).append(",");
}
if (args.length > 0) {
logMessage.deleteCharAt(logMessage.length() - 1);
}
logMessage.append(")");
log.info(logMessage.toString());
}
}
The code is working fine.
My problem is, even if I do some simple operations like, populating an array list within my code, even that information is getting logged. I don't want such information to be logged.
I want to log inputs only for the methods that I had written in the classes present in target package & not for the code written inside those methods. How do I achieve this?
You can use the below code which I had written months back to understand SNMP framework implementation, it prints i/o of all the methods in package and subpackage, you can remove irrelevant classes and modify according to your needs, if required.
#Aspect
public class Snmp4JProfiler {
private static final Logger LOG = LoggerFactory.getLogger(Snmp4JProfiler.class);
#Pointcut("execution (* org.snmp4j.Snmp.*(..))")
public void allSnmpServices() {
}
#Pointcut("execution (* org.snmp4j.security.U*.*(..))")
public void allUSMServices() {
}
#Around("allUSMServices() || allSnmpServices()")
public Object executionTimeOfService(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
String className = pjp.getSignature().getDeclaringTypeName();
final String methodName = methodSignature.getName();
String methodArgs = "";
for (Object obj : pjp.getArgs()) {
if (obj == null) {
methodArgs += "no args or null,";
} else if (obj instanceof UsmTimeEntry) {
UsmTimeEntry timeEntry = (UsmTimeEntry) obj;
methodArgs += obj.toString() + "[" + timeEntry.getEngineBoots() + "," + timeEntry.getLatestReceivedTime() + ","
+ timeEntry.getTimeDiff() + "," + timeEntry.getEngineID() + "]";
} else if (obj instanceof Object[]) {
methodArgs += obj.toString() + " " + Arrays.toString((Object[]) obj);
} else {
methodArgs += obj;
}
}
LOG.info("Start of method#" + methodName + " #class#" + className + " #args#" + methodArgs);
try {
Object output = pjp.proceed();
String rtValues = "";
if (output == null) {
rtValues += "no args or null,";
} else if (output instanceof UsmTimeEntry) {
UsmTimeEntry timeEntry = (UsmTimeEntry) output;
rtValues += output.toString() + "[" + timeEntry.getEngineBoots() + "," + timeEntry.getLatestReceivedTime() + ","
+ timeEntry.getTimeDiff() + "," + timeEntry.getEngineID() + "]";
} else if (output instanceof Object[]) {
rtValues += output.toString() + " " + Arrays.toString((Object[]) output);
} else {
rtValues += output;
}
LOG.info("End of method#" + methodName + " #class#" + className + " #return#" + rtValues);
return output;
} catch (Exception ex) {
LOG.info("End of method#" + methodName + " #class#" + className + " #error#" + ex.getMessage());
throw ex;
}
}
}
Related
I have a crawl function that also checks whether the content contains the param. If it contains I will write that to the database. How can I use the following code as a Read Job for the spring batch?
public void crawl(String baseUrl, String url, String postgresParam) {
if (!urls.contains(url) && url.startsWith(baseUrl)) {
// System.out.println(">> count: " + count + " [" + url + "]");
urls.add(url);
try {
Connection connection = Jsoup.connect(url).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
Elements linksOnPage = htmlDocument.select("a[href]");
bodyContent = htmlDocument.body().text();
String title = htmlDocument.title();
searchParameters(url, title);
// count++;
for (Element link : linksOnPage) {
crawl(baseUrl, link.absUrl("href"), postgresParam);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void searchParameters(String URL, String title) {
for (String param : postgresParamArray) {
if (bodyContent.toLowerCase().contains(param.toLowerCase())) {
System.out.println(">>>>>> Found: " + " [" + param + "]" + " [" + URL + "]" + " [" + title + "]");
}
}
}
this is my service code
public class Worker : BackgroundService
{
public bool isRegister { get; set; }
public bool checkIp { get; set; }
public long timePass { get; set; }
public Worker()
{
}
public override Task StartAsync(CancellationToken cancellationToken)
{
return base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (isRegister == false)
registerSelect();
if (checkIp == true)
{
checkIp = false;
await SecurityConfig.cacheServices?.BuildServiceProvider()?.GetService<IBlockFirewallIpService>().RegisterInFirewall();
}
timePass += 1000;
if (timePass % 60000 == 0)
await SecurityConfig.cacheServices?.BuildServiceProvider()?.GetService<IBlockFirewallIpService>().RegisterInFirewall();
await Task.Delay(1000, stoppingToken);
}
}
public void registerSelect()
{
isRegister = true;
using (SqlConnection conn = new SqlConnection(GetDbConnection()))
{
conn.Open();
SqlDependency.Start(GetDbConnection());
string commandText = "SELECT [Ip1],[Ip2] ,[Ip3] ,[Ip4] FROM dbo.BlockFirewallIps where IsRead is null";
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Insert)
checkIp = true;
SqlDependency temp = sender as SqlDependency;
if (temp != null)
temp.OnChange -= new OnChangeEventHandler(OnDependencyChange);
registerSelect();
}
private string GetDbConnection()
{
return GlobalConfig.Configuration["ConnectionStrings:DefaultConnection"];
}
}
and this is my IBlockFirewallIpService.RegisterInFirewall() code
public async Task RegisterInFirewall()
{
var allBlockIps = await db.BlockFirewallIps.Where(t => t.IsRead == null).ToListAsync();
foreach (var ip in allBlockIps)
{
BanIP("OjeFirTCP" + ip.Ip1 + "_" + ip.Ip2 + "_" + ip.Ip3 + "_" + ip.Ip4, ip.Ip1 + "." + ip.Ip2 + "." + ip.Ip3 + "." + ip.Ip4, "Any", "TCP");
BanIP("OjeFirUDP" + ip.Ip1 + "_" + ip.Ip2 + "_" + ip.Ip3 + "_" + ip.Ip4, ip.Ip1 + "." + ip.Ip2 + "." + ip.Ip3 + "." + ip.Ip4, "Any", "UDP");
ip.IsRead = true;
db.SaveChanges();
}
}
void BanIP(string RuleName, string IPAddress, string Port, string Protocol)
{
if (OperatingSystem.IsWindows())
{
if (!string.IsNullOrEmpty(RuleName) && !string.IsNullOrEmpty(IPAddress) && !string.IsNullOrEmpty(Port) && !string.IsNullOrEmpty(Protocol) && new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
{
using (Process RunCmd = new Process())
{
RunCmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
RunCmd.StartInfo.FileName = "cmd.exe";
RunCmd.StartInfo.Arguments = "/C netsh advfirewall firewall add rule name=\"" + RuleName + "\" dir=in action=block remoteip=" + IPAddress + " remoteport=" + Port + " protocol=" + Protocol;
RunCmd.Start();
}
}
}
}
this is progeram.cs
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService(options =>
{
options.ServiceName = "OjeFirewall";
})
.ConfigureServices((hostContext, services) =>
{
GlobalConfig.Configuration = hostContext.Configuration;
services.AddScoped<IHttpContextAccessor, FakeIHttpContextAccessor>();
SecurityConfig.Config(services);
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();
this is SecurityConfig.Config codes
services.AddDbContext<SecurityDBContext>(options =>
options.UseSqlServer(GlobalConfig.Configuration["ConnectionStrings:DefaultConnection"],
b => b.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery))
, ServiceLifetime.Singleton
);
services.AddSingleton<IIpLimitationWhiteListService, IpLimitationWhiteListService>();
services.AddSingleton<IIpLimitationBlackListService, IpLimitationBlackListService>();
services.AddSingleton<IFileAccessRoleService, FileAccessRoleService>();
services.AddSingleton<IRoleService, RoleService>();
services.AddSingleton<IBlockClientConfigService, BlockClientConfigService>();
services.AddSingleton<IBlockAutoIpService, BlockAutoIpService>();
services.AddSingleton<IBlockFirewallIpService, BlockFirewallIpService>();
the problem :
this code using too much memory after 3 day
starting ram usage is 20mb after first call (OnDependencyChange) it use 47mb
after 3 day it use 178mb
where i am doing wrong ?!
i found problem
await SecurityConfig.cacheServices?.BuildServiceProvider()?.GetService<IBlockFirewallIpService>().RegisterInFirewall();
this line code was the problem after change it to normal injection ram usage is stable now, but i can not understand whay !?
I have created a simple Spring-boot application with two entities as Company.java and User.java. These two has #OneToMany relationship. And I have a created a test file for generating typescript file with printing those two entity's attributes. Here is the my test case.
#Inject
RepositoryRestMvcConfiguration configuration;
#Test
public void getEndPoints() {
configuration.resourceMappings().forEach(c -> {
String className = c.getDomainType().getName();
try {
Class<?> entityClass = Class.forName(className);
Field[] fields = entityClass.getDeclaredFields();
File tsClassDir = new File("data/tsClass");
File tsClass = new File(tsClassDir, entityClass.getSimpleName() + ".ts");
if (!tsClass.getParentFile().exists()) {
tsClass.getParentFile().mkdirs();
}
tsClass.createNewFile();
String code = "export interface " + entityClass.getSimpleName() + "{\n";
for (Field field : fields) {
try {
NotNull notNullAnnotation = field.getDeclaredAnnotation(NotNull.class);
Class<?> filedClass = Class.forName(field.getType().getName());
if (notNullAnnotation == null){
code += "\t" + field.getName() + "?: " + filedClass.getSimpleName().trim() + ";" + "\n";
}else{
code += "\t" + field.getName() + ": " + filedClass.getSimpleName().trim() + ";" + "\n";
}
} catch (Exception e) {
// TODO: handle exception
}
// System.err.println(field.getName());
}
code += "}";
Files.write(tsClass.toPath(), code.getBytes());
System.err.println(code);
} catch (Exception e) {
// TODO: handle exception
}
});
}
After test run I got the result given below.
export interface User{
userName: String;
password: String;
email: String;
company?: Company;
}
export interface Company{
name: String;
email: String;
users?: Set;
}
But I need to print that Company and User has #OneToMany relationship in the typescript file. How do I do that?
hi here is my code i want to call the insert(latitude,longitude) inside the get() but it is not working for me so please help!
public void onStart(Intent intent, int startid){
Toast.makeText(getApplicationContext(),"Service Strated...",Toast.LENGTH_SHORT).show();
device_id = intent.getExtras().getString("device_id");
final int delay = 60000; //milliseconds
h.postDelayed(new Runnable() {
public void run() {
try {
get();
} catch (JSONException e) {
e.printStackTrace();
}
h.postDelayed(this, delay);
}
}, delay);
}
public void get() throws JSONException {
count++;
gps=new GPSTracker(getApplicationContext());
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if (latitude != 0.0 & longitude != 0.0) {
insert(latitude,longitude);
Toast.makeText(getApplicationContext(), "Your Location : \n Lat :" + latitude + "\nLang :" + longitude, Toast.LENGTH_LONG).show();
if(count==5){
send();
count=0;
}
}
}
}
public void insert(double lat,double lon){
System.out.print("hi_entered");
boolean exist = checkIfExist(lat, lon);
System.out.print(exist);
if(!exist) {
System.out.print("INSERT INTO location VALUES(null,'" + lat + "','" + lon + "',null);");
db.execSQL("INSERT INTO location VALUES(null,'" + lat + "','" + lon + "',null);");
}
}
I'm trying to write down something more sophisticated than simple Fahrenheit to Celsius and vice versa converter. I'm trying to use JoptionPane for better fell but I'm stuck in one place and have no idea how to resolve this (line 32 and 37 - method not applicable for the arguments ()) any help will be appreciated.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class ex74v3 {
public static void main(String[] args) {
temp();
new ex74v3();
}
public ex74v3() {
boolean done=false;
while(!done){
done=true;
String[] ans=new String[11];
String[] choice={
"(°F) to (°C)",
"(°C) to (°F)",
};
int choice_indx=JOptionPane.showOptionDialog(null, "Choose type of conversion", "Choice",
0,JOptionPane.QUESTION_MESSAGE ,
null,choice,0);
ans[0]=choice[choice_indx];
if(choice_indx==1 || choice_indx==2) {
done=false;
}else{
choice_indx=JOptionPane.showMessageDialog(null, "Fahrenheit to Celsius: " + baseFtC() + " (°C)");
}
if(choice_indx==2) {
done=false;
}else{
choice_indx=JOptionPane.showMessageDialog(null, "Celsius to Fahrenheit : " + baseCtF() + " (°F)");
}
}
}
public static int temp() {
String value = JOptionPane.showInputDialog(null, "Enter value ");
#SuppressWarnings("unused")
int log;
return log = Integer.parseInt(value);
}
public int baseCtF(int value) {
int conversion = (int) (temp() * 1.8 + 32);
return conversion;
}
public int baseFtC(int value) {
int conversion = (int) ((temp() - 32) / 1.8);
return conversion;
}
}
Ok, there is an other way, easier, thanks anyway ;]
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ex74v4 {
public static void main(String[] a) {
DecimalFormat digit = new DecimalFormat("0.00");
String value = JOptionPane.showInputDialog(null, "Enter value ");
float log;
log = Float.parseFloat(value);
JFrame frame = new JFrame();
Object stringArray[] = { "Celsius to Fahrenheit", "Fahrenheit to Celsius" };
int reply = JOptionPane.showOptionDialog(frame, "Choose conversion type of value: " + digit.format(log), "MiniConverter",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray,
stringArray[0]);
if (reply == JOptionPane.YES_OPTION) {
DecimalFormat digit2 = new DecimalFormat("0.00");
double conversion = log * 1.8 + 32;
JOptionPane.showMessageDialog(frame, log + " " + "(°C) equals " + digit2.format(conversion) + " (°F)", "MiniConverter", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else {
DecimalFormat digit3 = new DecimalFormat("0.00");
double conversion = (log - 32) / 1.8;
JOptionPane.showMessageDialog(frame, log + " " + "(°F) equals " + digit3.format(conversion) + " (°C)", "MiniConverter", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}