Hard-Coding using JavaDB, and netbeans. I wrote a simple table, then I wrote a simple java program to run and connect to the database, code seems to be running well. I wrote the code hard-coded purposefully with the username/password to the database. Wrote the code, an, awesome. I am using terminal and javap -c, with DriverManager.getConnection(url, "username", "password. ");o read all the file, Im hoping that's considered hard-coded hacking, I need a way to mitigate it, or patch it. I was looking at Argon2 for java, but simply can't understand it yet. These are pics of running the code, connection, database, and in terminal I ran javap -c and it red me out the username/password info, how can I block. AlsoI installed a Debugging Plugin into NB tjat worked once and did like javap, but it's only worked once. if some one could help me with it or a dfferent type of mitigation - patch Id really appreciate it.
Main Code with exception:
import java.sql.SQLException;
public class HardCodeMitigation {
public static void main(String[] args) throws SQLException {
// TODO code application logic here
abc a1 = new abc();
}
}
Second code w/DriverMan with passwords Hard-coded
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
class abc {
public abc() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/IT_Entity", "cain", "cain");
System.out.println("Connection Created");
}
}
Javap - c showing passwords: Chads - MacBook - Pro: ~chadbyars$ cd / Users / chadbyars / NetBeansProjects / hardcodemitigation / src
Chads - MacBook - Pro: src chadbyars$ javac abc.java
Chads - MacBook - Pro: src chadbyars$ java abc
Error: Main method not found in class abc, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Chads - MacBook - Pro: src chadbyars$ javap - c abc
Compiled from "abc.java"
class abc {
public abc() throws java.sql.SQLException;
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: ldc # 2 // String jdbc:derby://localhost:1527/IT_Entity
6: ldc #3 // String cain
8: ldc # 3 // String cain
10: invokestatic #4 // Method java/sql/DriverManager.getConnection:(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/sql/Connection;
13: astore_1
14: getstatic # 5 // Field java/lang/System.out:Ljava/io/PrintStream;
17: ldc #6 // String Connection Created
19: invokevirtual # 7 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
22: return
}
Chads - MacBook - Pro: src chadbyars$
Related
The same code worked perfectly with JDK 11. Switching to JDK 17 makes the test fail, since Instant.now() returns null.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
#Test
void mockStatic() {
final Instant instantExpected = Instant.parse("2022-03-10T10:15:30Z");
final Clock spyClock = spy(Clock.class);
when(spyClock.instant()).thenReturn(instantExpected);
try (final MockedStatic<Clock> clockMock = mockStatic(Clock.class)) {
clockMock.when(Clock::systemUTC).thenReturn(spyClock);
final Instant now = Instant.now();
assertEquals(instantExpected, now);
}
}
Running on Windows 10, Mockito 4.6.1, Eclipse Temurin 17.0.2.8
The difference stems from the fact that JDK 17 no longer calls Clock.systemUTC() in implementation of Instant.now()
Please compare:
JDK 17:
public static Instant now() {
return Clock.currentInstant();
}
JDK 15:
public static Instant now() {
return Clock.systemUTC().instant();
}
If you insist on mocking static methods, you could stub Instant.now(), not Clock.systemUTC() - thus you don't rely on the implementation of Instant.now()
As discussed in the comments in under your post, this is not the recommended approach - class Clock was designed specifically to make time-handling code easier to test, use a Clock in your code instead of calling Instant.now()
#Test
void mockStaticClock() {
final Instant instantExpected = Instant.parse("2022-03-10T10:15:30Z");
try (final MockedStatic<Instant> instantMock = mockStatic(Instant.class)) {
instantMock.when(Instant::now).thenReturn(instantExpected);
final Instant now = Instant.now();
assertEquals(instantExpected, now);
}
}
I use this tutorial to connect to Gmail API: https://developers.google.com/gmail/api/quickstart/java
I would like to make a keyword in Katalon Studio, which depends on Gmail API.
I modified from sample code that line:
InputStream in = GmailQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
to this:
InputStream ins = new FileInputStream(CREDENTIALS_FILE_PATH);
JAR files are added, project is running and browser window is opened to get token. After successful authorization I got error message:
Caused by: java.lang.NoSuchMethodError:
com.google.api.client.http.HttpRequest.setResponseReturnRawInputStream(Z)Lcom/google/api/client/http/HttpRequest;
UPDATE: List of imported dependencies:
commons-codec-1.15.jar
commons-logging-1.2.jar
google-api-client-1.31.3.jar
google-api-client-extensions-1.6.0-beta.jar
google-api-client-jackson2-1.31.3.jar
google-api-client-java6-1.31.3.jar
google-api-services-gmail-v1-rev110-1.25.0.jar
google-http-client-1.39.1.jar
google-http-client-jackson2-1.39.1.jar
google-oauth-client-java6-1.31.4.jar
google-oauth-client-jetty-1.31.4.jar
guava-30.1.1-jre.jar
httpclient-4.5.13.jar
httpcore-4.4.14.jar
j2objc-annotations-1.3.jar
jackson-core-2.12.2.jar
jsr305-3.0.2.jar
https://docs.katalon.com/katalon-studio/docs/external-libraries.html#exclude-built-in-libraries
With the ability to remove built-in libraries stored in the .classpath file of a project folder, you can replace a built-in library with an external one for flexible libraries usage in a test project.
Requirements
An active Katalon Studio Enterprise license.
Katalon Studio version 7.8.
UPD:
i got katalon 7.9.1 and here how i was able to do it:
add the following class into KS project:
include/scripts/groovy/(default package)/GroovyBox.java
import groovy.lang.*;
import java.util.regex.Pattern;
import java.util.Map;
import java.util.List;
/** run groovy script in isolated classloader*/
public class GroovyBox {
GroovyShell gs;
public GroovyBox(ClassLoader parentCL, Pattern excludeClassPattern ) {
FilteredCL fcl = new FilteredCL(parentCL, excludeClassPattern);
gs = new GroovyShell(fcl);
}
public GroovyBox withClassPath(List<String> classPathList) {
GroovyClassLoader cl = gs.getClassLoader();
for(String cp: classPathList) cl.addClasspath(cp);
return this;
}
public Script parse(String scriptText) {
return gs.parse(scriptText);
}
public static class FilteredCL extends GroovyClassLoader{
Pattern filterOut;
public FilteredCL(ClassLoader parent,Pattern excludeClassPattern){
super(parent);
filterOut = excludeClassPattern;
}
#Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException{
if(filterOut.matcher(name).matches())throw new ClassNotFoundException("class not found "+ name);
return super.loadClass(name, resolve);
}
}
}
now add a test case - actually you can move code from test case into a class...
import ... /* all katalon imports here*/
assert method1() == 'HELLO WORLD'
def method1() {
def gb = new GroovyBox(this.getClass().getClassLoader().getParent(), ~/^com\.google\..*/)
def script = gb.parse('''
#Grab(group='com.google.api-client', module='google-api-client', version='1.31.3')
import com.google.api.client.http.HttpRequest
def c = HttpRequest.class
println( "methods execute:: "+c.methods.findAll{it.name=='execute'} )
println( "methods setResponseReturnRawInputStream:: "+c.methods.findAll{it.name=='setResponseReturnRawInputStream'} )
println greeting
return greeting.toUpperCase()
''')
script.setBinding([greeting:'hello world'] as Binding)
return script.run()
}
options to define external dependencies:
#Grab(...) as a first line of parsed script - loads all required dependencies from maven central (by default). for example #Grab(group='com.google.api-client', module='google-api-client', version='1.31.3') corresponds to this artifact.
sometimes you need to specify specific maven repository then add #GrabResolver(name='central', root='https://repo1.maven.org/maven2/')
if you want to specify local file dependencies then in the code above:
def gb = new GroovyBox(...).withClassPath([
'/path/to/lib1.jar',
'/path/to/lib2.jar'
])
I am learning groovy now. And in my case some simple code with trait is not working.
Here's code:
trait Mark {
void DisplayMarks() {
println("Display Marks");
}
}
public class MarkOwner implements Mark {
int StudentID
int Marks1;
static void main(String[] args) {
MarkOwner m = new MarkOwner();
m.DisplayMarks();
}
}
And here's error:
msangel#msangel-np6:~/work/groov$ groovy scr2.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/home/msangel/work/groov/scr2.groovy: 2: Method definition not expected here. Please define the method at an appropriate place or perhaps try using a block/Closure instead. at line: 2 column: 4. File: /home/msangel/work/groov/scr2.groovy # line 2, column 4.
void DisplayMarks() {
^
1 error
I was also looked to different tutorial but the syntax seems to be correct.
Here s my default groovy version number:
msangel#msangel-np6:~/work/groov$ groovy --version
Groovy Version: 1.8.6 JVM: 1.8.0_91 Vendor: Oracle Corporation OS: Linux
I am newbie for cucumber framework, I have worked on selenium webdriver using testNG framework. I have to start cucumber framework, I have installed cucumber plugin to eclipse but dont know how to start writting code.
And what is the difference between cucumber and cucumber-jvm, and which is the best?
Could anyone pls help me out?
Thanks in advance.
You can find lots of info on what dependecies you should use for your project on the Cucumber main site Cucumber Documentation
Cucumber base is Ruby
Cucumber-JVM is Java
start with creating a src/test/resources
create a file named anything you want (keep it to the thing you want to test) and end it with .feature
Feature: Calculator should work accourding to standard calculator devices
Scenario: addition
Given a calculator I just turned on
When I add 4 and 5
Then the result is 9
put this in as a guide line and try to run it. it should give you a call missing steps.
create a new java file in src/test/java and call it RunCukesTest this wil later be the starter of all your features.
the output you just got from the feature in the console can be put in a .java call it something to do with the feature like CalculatorSteps.java put this in the same folder as your RunCukesTest.java
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(
monochrome = false,
plugin = {"pretty","json:target/cucumber.json"} ,
features = "src/test/resources/cucumber",
tags = "~#ignore"
)
public class RunCukesTest {
}
this is the basic you need to start using Cucumber (there is a start example on github)
Now the Selenium question
you will have to initiate a WebDriver _driver;
with driver you create a new ChromeDriver or FireFoxDriver etc
some browsers need a installation ChromeDriver firefox is built in (to my best knowledge)
see the code below
ask if there is anything you don't get
import java.util.concurrent.TimeUnit;
import cucumber.api.java.en.*;
import org.eclipse.jetty.util.thread.Timeout;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NavigationSteps {
WebDriver _driver;
#Given("^i am at \"([^\"]*)\"$")
public void i_am_at_home(String arg1) throws Throwable {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
_driver = new ChromeDriver();
_driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
_driver.get(arg1);
Thread.sleep(500);
}
#When("^i click on \"([^\"]*)\"$")
public void i_click_on(String arg1) throws Throwable {
_driver.findElement(By.linkText(arg1)).click();
Thread.sleep(500);
}
#Then("^i expect the title to be \"(.*?)\"\"(.*?)\"$")
public void i_expect_the_title_to_be(String arg1, String arg2) throws Throwable {
String result = (arg1 + " | " + arg2);
Thread.sleep(200);
assertEquals("Title should be",result,_driver.getTitle());
tearDown();
}
#Then("^Header should contain \"(.*?)\"$")
public void header_should_contain(String arg1) throws Throwable {
Thread.sleep(200);
assertEquals("Title should be", arg1, _driver.findElement(By.xpath(".//*[#id='main']/div[1]/div/h1")).getText());
tearDown();
}
#After
public void tearDown() throws InterruptedException
{
_driver.quit();
}
}
EDIT - answers to the questions in nicer format
feature file calls the java file (Run via RunCukesTest or feature file)
the methods to test go into je java steps file
Feature calculator has a CalculatorSteps.java file the scenario is in the feature file the methods in the steps
No, the console outputs this as a Regex to identify the corresponding step the test u write in the method below it.
Given a calculator I just turned on
results into
#Given ("^a calculator I just turned on$")
public void iCanCallThisAnythingIWant(){
#do something
}
see answer 2
Given When Then are the logical way to read a Scenario to keep things readable it should be used in that way. If you find yourself with a long Given When or Then u can split the sentence with a "and" in between. but it doesn't matter in what way u write them.
I am using Soap UI (Free version) v4.6.4. One of the test steps in my test case is to declare a class, which should be referred further in other groovy test steps; create instances and such. But to start with I tried the following in test step named ts01:
class SomeClass {
private String name
public SomeClass(String name) {
this.name = name
}
public print() {
log.info "SomeClass.print - " + this.name
}
}
// After the class definition, in the same groovy script
context.project = "myproject"
context.scinst = new SomeClass("hello")
log.info context
When I run this test step separately, I get the following error popup:
java.lang.NoClassDefFoundError: Could not initialize class SomeClass
error at line: XX
and randomly popping another error:
java.lang.ExceptionInInitializerError
When I run this test step as part of the test case, it runs but context.scinst is not available.
What am I missing? Why is SomeClass not available even though it is defined?
Your help is highly appreciated.
Thanks
Vivek Ragunathan