23 Eylül 2019 Pazartesi

RSAPublicKey Arayüzü

constructor
Şöyle yaparız.
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);

KeyPair keyPair = generator.generateKeyPair();

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
getEncoded metodu
byte[] döndürür. Bunu Base64 olarak saklamak için şöyle yaparız.
String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
Geri döndürmek için şöyle yaparız.
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey2 = keyFactory.generatePublic(spec);

20 Eylül 2019 Cuma

RMI Remote Arayüzü

Giriş
Şu satırı dahil ederiz
import java.rmi.Remote;
import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject;
Bu arayüzden kalıtan sınıflar uzaktaki bir bilgisayardan çağrılabilir. 

Kullanım
Önce bir arayüz tanımlarız. Buna "Defining the Contract" deniliyor
public interface FooService extends Remote {
  void bar() throws RemoteException;
}
Açıklaması şöyle
This interface extends the java.rmi.Remote marker interface.
In addition, each method declared in the interface throws the java.rmi.RemoteException:
Note, though, that RMI supports the full Java specification for method signatures, as long as the Java types implement java.io.Serializable.
Daha sonra bu arayüzü gerçekleştiren sınıfı yazarız
public class FooServiceImpl implements FooService {
public bar() {...}
}
Açıklaması şöyle
Notice, that we've left off the throws RemoteException clause from the method definition.

It'd be unusual for our remote object to throw a RemoteException since this exception is typically reserved for the RMI library to raise communication errors to the client.

Leaving it out also has the benefit of keeping our implementation RMI-agnostic.
Tüm Kod
Bu servisi başlatmak ve durdurmak için şöyle yaparız. Burada kodun Foo sınıfı içinde olduğunu varsaydık. Server sınıfımız UnicastRemoteObject sınıfından kalıtmadığı için UnicastRemoteObject.exportObject() çağrısı yapma gerekti.
Registry registry;
int port = 52100;
String BINDING_NAME = "Foo";

public void startService() {
  FooService foo = (FooService) UnicastRemoteObject.exportObject(this,0);
  try {
    registry = LocateRegistry.createRegistry(port);
  } catch (Exception e){
    ...
  }

  registry.rebind (BINDING_NAME,foo);

}

public void stopService() {
  try {
    UnicastRemoteObject.unexportObject(this,true);
    registry.unbind(BINDING_NAME);
  } catch (NoSuchObjectException | NotBoundtException | AccessException e){
...
  }
}
Creating Stub
Eğer bir başka sınıfta kodlasaydık şöyle yaparız
FooService server = new FooServiceImpl();
FooService stub = (FooService) UnicastRemoteObject.exportObject(server, 0);
Açıklaması şöyle
We use the static UnicastRemoteObject.exportObject method to create our stub implementation. The stub is what does the magic of communicating with the server over the underlying RMI protocol.

The first argument to exportObject is the remote server object.

The second argument is the port that exportObject uses for exporting the remote object to the registry.

Giving a value of zero indicates that we don't care which port exportObject uses, which is typical and so chosen dynamically.

Unfortunately, the exportObject() method without a port number is deprecated.
Creating a Registry
Şöyle yaparız
Registry registry = LocateRegistry.createRegistry(52100);
Açıklaması şöyle. Burada Registry server stub'ın çalışacağı bilgisayarda
We can stand up a registry local to our server or as a separate stand-alone service.

For simplicity, we'll create one that is local to our server:

Also, we've used the createRegistry method, since we are creating the registry local to the server.

By default, an RMI registry runs on port 1099. Rather, a different port can also be specified in the createRegistry factory method.

But in the stand-alone case, we'd call getRegistry, passing the hostname and port number as parameters.
Binding the Stub
Şöyle yaparız
registry.rebind("MessengerService", stub);
Açıklaması şöyle. Burada Registry server stub'ın çalışacağı bilgisayarda
An RMI registry is a naming facility like JNDI etc. 
...
As a result, the remote object is now available to any client that can locate the registry.
Creating the Client
Şöyle yaparız
Registry registry = LocateRegistry.getRegistry();

MessengerService server = (MessengerService) registry.lookup("MessengerService");

String responseMessage = server.sendMessage("Client Message");

String expectedMessage = "Server Message";
 
assertEquals(expectedMessage, responseMessage);
Açıklaması şöyle. Burada Registry server stub'ın çalışacağı bilgisayarda
Because we're running the RMI registry on the local machine and default port 1099, we don't pass any parameters to getRegistry.

Indeed, if the registry is rather on a different host or different port, we can supply these parameters.

Once we lookup the stub object using the registry, we can invoke the methods on the remote server.
RMI Sunucusunun Her Bir Bağlanan Client'ı Tetiklemesi
Her client UnicastRemoteObject sınıfından ve IFooClient tarzı bir arayüzü gerçekleştirirse, client kendisini sunucuya gönderir ve sunucu IFooClient listesi tutar. Bu listedeki her nesneyi periyodik olarak tetiklerse, client'ın ayakta olup olmadığını anlar. Client'ı tetiklemek için de IFooClient'a ait bir metodu çağırır.

19 Eylül 2019 Perşembe

Selenium WebDriver Arayüzü

Giriş
Şu satırı dahil ederiz.
import org.openqa.selenium.WebDriver;
Her Driver aynı zamanda JavaScripExecutor'a çevrilebilir.

Genel Kullanım
Örnek
Şöyle yaparız
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserSelection {
  static WebDriver driver;

  public static WebDriver usingChrome() {
    System.setProperty("webdriver.chrome.driver",
      "E:\\SeleniumLibs\\\\chromedriver_win32\\chromedriver.exe"); 
    driver = new ChromeDriver(); 
    driver.manage().window().maximize();
    return driver;
  } 
}

public class MakeMyTripDateTest {
  WebDriver driver;

  @BeforeMethod
  public void openBrowser(){ 
    driver = BrowserSelection.usingChrome(); 
  }

  @AfterMethod
  public void closeBrowser(){
    driver.quit();
  }
}
constructor - Chrome
Chrome için şu satırı dahil ederiz.
import org.openqa.selenium.chrome.ChromeDriver;
Testi başlatmadan önce setUp() kısmında System.setProperty() çağrısı ile webdriver.chrome.driver değişkenini atamak gerekir.

Örnek
Şöyle yaparız.
System.setProperty("webdriver.chrome.driver",
"C:\Selenium\\browser\\chromedriver.exe");
WebDriver driver =  new ChromeDriver();
Örnek
Burada Chrome Driver'ın path'ini veriyoruz. Chrom kurulumunu değil! Şu kod yanlış
System.setProperty("webdriver.chrome.driver",
 "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
WebDriver driver = new ChromeDriver();
Şöyle yaparız.
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Örnek - ChromeOptions
Şöyle yaparız.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class W3c {
  public static void main(String[] args) throws Exception {
    ChromeOptions opt = new ChromeOptions();
    opt.setExperimentalOption("w3c", true);
    ChromeDriver driver = new ChromeDriver(opt);
    driver.get("https://www.google.co.in");
  }
}
constructor - Firefox
Şu satırı dahil ederiz.
import org.openqa.selenium.firefox.FirefoxDriver;
Testi başlatmadan önce setUp() kısmında System.setProperty() çağrısı ile webdriver.gecko.driver değişkenini atamak gerekir.

Örnek
Şöyle yaparız
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "null");
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\Drivers\\geckodriver.exe");
driver = new FirefoxDriver();
constructor - Edge
Şu satırı dahil ederiz.
import org.openqa.selenium.edge.EdgeDriver;
Testi başlatmadan önce setUp() kısmında System.setProperty() çağrısı ile webdriver.edge.driver değişkenini atamak gerekir.

Örnek
Şöyle yaparız.
System.setProperty("webdriver.edge.driver", "C:\\Users\\Foo\\Downloads\\
  MicrosoftWebDriver.exe");
WebDriver driver = new EdgeDriver();
Örnek - RemoteWebDriver
Şöyle yaparız
import org.openqa.selenium.remote.RemoteWebDriver;
 
/*
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
*/

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("build", "[Java] ...");
capabilities.setCapability("name", "[Java] ...");
capabilities.setCapability("platform", "Windows 10");
capabilities.setCapability("browserName", "Chrome");
capabilities.setCapability("version","85.0");
capabilities.setCapability("tunnel",false);
capabilities.setCapability("network",true);
capabilities.setCapability("console",true);
capabilities.setCapability("visual",true);
 
WebDriver driver = new RemoteWebDriver(new URL("http://..."), capabilities);
findElement metodu
Şu satırı dahil ederiz. WebElement nesnesi döner.
import org.openqa.selenium.By;
Python ayrı byXXX metodları kullandığı için bence daha okumaklı. Şöyle yaparız. Java da ise By.XXX şeklinde kullanılır.
chromedriver = webdriver.Chrome()
...
elem = chromedriver.find_element_by_class_name("twelve-days-claim")

elem2 = chromedriver.find_element_by_class_name("login-popup")

username = chromedriver.find_element_by_css_selector("div[id*='form-login']
  [id='login-form-email'] input")
Selenium By Sınıfı yazısına taşıdım.

findElements metodu
Açıklaması şöyle.
This method is affected by the 'implicit wait' times in force at the time of execution. When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.
Örnek
Elimizde bir XPath olsun.
String path = "/html/body/div/div[3]/tr[1]/th";
Şöyle yaparız.
List <WebElement> pagination= driver.findElements(By.xpath(path));
Örnek
Şöyle yaparız.
List<WebElement> options = driver.findElements(by.xpath(" your locator"));
for(WebElement element : options){
  if(element.getText().equals(" your value from drop down")){
    element.click();
  }
}  
get metodu
Şöyle yaparız.
driver.get("https://www.snapdeal.com/");
getWindowHandle metodu
Şöyle yaparız.
String parentWindowHandler=driver.getWindowHandle();// Store your parent window
getWindowHandles metodu
Örnek
Şöyle yaparız.
// Store the current window handle
String mainWin = driver.getWindowHandle();

// Perform the click operation that opens new window

//Wait till driver.getWindowHandles() returns 2 windows

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}
//Get current window to take decision on the next actions
String currentWin= driver.getWindowHandle();

// Perform the actions on new window

// Close the new window
driver.close();

// Switch back to original first window
driver.switchTo().window(mainWin);
Örnek
Şöyle yaparız.
//store parent window value in string
String parentWindow = driver.getWindowHandle();

//store the set of all windows
Set<String> allwindows= driver.getWindowHandles();

for (String childWindow : allwindows) {
  if(!childWindow.equals(parentWindow))
  {
    driver.switchTo().window(childWindow);
    System.out.println("child window");
    System.out.println(driver.getTitle());      
    // do some operation
    //Closing the Child Window.
    driver.close();    
  }
}
driver.switchTo().window(parentWindow);
manage metodu
WebDriver.Options Arayüzü döndürür.

navigate metodu
Şöyle yaparız.
driver.navigate().back();
quit metodu
Şöyle yaparız.
driver.quit();
switchTometodu
alert, frame, window için kullanılabilir.
Örnek
popup varsa şöyle yaparız.
driver.switchTo().alert().accept();
Örnek
Şöyle yaparız.
driver.switchTo().frame("iframeResult");
Örnek
Şöyle yaparız.
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
  subWindowHandler = iterator.next();
}

driver.switchTo().window(subWindowHandler); // switch to popup window