How do i set desired capabilities externally source (without hard coding); - frameworks

public void setUp() throws MalformedURLException,InterruptedException
{
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("newCommandTimeout", 100000);
capabilities.setCapability("BROWSER_NAME", "Android");
capabilities.setCapability("platformVersion", "8.1.0");
capabilities.setCapability("deviceName", "a1cc6f96");
capabilities.setCapability("platformName", "Android");
}

Create the config.properties file in the project. Add following data in the config.properties file
newCommandTimeout = 100000
browserName = chrome
platformVersion = 8.1.0
deviceName = a1cc6f96
platformName = Android
Then add the method that will return the property value
public class LoadProperty {
Properties prop = new Properties();
InputStream input = null;
public String getProperty (String propertyName){
try {
input = new FileInputStream("path/to/config file/config.properties");
prop.load(input);
return prop.getProperty(propertyName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
After that you can use the property like following
LoadProperty prop =new LoadProperty();
String newCommandTimeout = prop.getProperty("newCommandTimeout");
String browserName = prop.getProperty("browserName");
String platformVersion = prop.getProperty("platformVersion");
String deviceName = prop.getProperty("deviceName");
String platformName = prop.getProperty("platformName");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("newCommandTimeout", newCommandTimeout);
capabilities.setCapability("BROWSER_NAME", browserName);
capabilities.setCapability("platformVersion", platformVersion);
capabilities.setCapability("deviceName", deviceName);
capabilities.setCapability("platformName", platformName);

Related

How to generate signature using hash string using iTextSharp and c#

I am trying to add public key string in MakeSignature.SignExternalContainer but having error,
string sing_test = "MIIFMTCCBBmgAwIBAgICMF8wDQYJKoZIhvcNAQELBQAwfDELMAkGA1UEBhMCSU4xKjAoBgNVBAoTIU5TREwgZS1Hb3YgSW5mcmFzdHJ1Y3R1cmUgTGltaXRlZDEdMBsGA1UECxMUQ2VydGlmeWluZyBBdXRob3JpdHkxIjAgBgNVBAMTGU5TRExlR292SXNzdWluZ0NBMjAxNlRlc3QwHhcNMTcwMTI4MDkwOTEzWhcNMTcwMTI4MDkzODEzWjCCARgxCzAJBgNVBAYTAklOMR0wGwYDVQQDExRNQU5JU0ggR0lSSVNIIEJFTkRSRTEpMCcGA1UEQRMgMjUxYjkyYjkxZjllNDBmOGE2YmVlZjZiMDgyMzYyZGYxNjA0BgNVBC0DLQBsbnlOOVVuNzE5S1NKNnpaQVNtUGZaUlJpYTVuTXBLSEV0cs3ZidAmwZQKbBmUKLoeD8nCDIUZZR9Am2pwSnar7WtB2MA74Sz4U2xzifNsh22YPd+ySbGqJtUd9xbhlQIDAQABo4IBHTCCARkwEQYDVR0OBAoECEwFNGCDXdKgMIG7BgNVHSAEgbMwgbAwga0GB2CCZGQCBAIwgaEwQQYIKwYBBQUHAgEWNWh0dHBzOi8vbnNkbC5lZ292LWNhLmNvLmluL3JlcG9zaXRvcnkvbnNkbGVnb3ZjcHMucGRmMFwGCCsGAQUFBwICMFAaTkFhZGhhYXIgZS1LWUMtQmlvbWV0cmljIENsYXNzIENlcnRpZmljYXRlIElzc3VlZCBieSBOU0RMIGUtR292IElzc3VpbmcgQ0EgVGVzdDAhBgNVHREEGjAYgRZtYW5pc2hiZW5kcmVAZ21haWwuY29tMBMGA1UdIwQMMAqACEBuFJI2LqIcMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsFAAOCAQEADbuOkgWKquflIrqDsB93L5aa+VxjFHvB914UDIllO4MYTo/UVgDN2iANiJ2HOjFkY0VhdnuJKp0cjDSywP6mTXs0VUf70DEL5sZpjfnoJK++Eb6FlDHHMKflMkG/ja3b6FWK1W/1L0/yjYpjl4E2Uu5tq0T3k4ZOPd/LBD3OeudKZM1IPaT95Zd8JRqwz6LsyYx1SvXqLtrRUb8eIauvAJ92prvovxusvupzolB3AOCkwEr6jqGXOiwssEnqUCuUd3CVXWUxL5TzWW9oCPIDAKbUyyVWtntorVFfKmzvWDCV42jkHrf9J1snbr4DyjNhkOSQr6cDZfg0uK2gKWfBcA==";
byte[] rawData = System.Convert.FromBase64String(sing_test );
public static byte[] GetBytesToSign(string unsignedPdf, string tempPdf, string signatureFieldName)
{
using (PdfReader reader = new PdfReader(unsignedPdf))
{
using (FileStream os = File.OpenWrite(tempPdf))
{
PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(36, 748, 144, 780), 1, signatureFieldName);
IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
MakeSignature.SignExternalContainer(appearance, external, 8192);
stamper.Close();
return SHA1Managed.Create().ComputeHash(appearance.GetRangeStream());
}
}
}
public static void EmbedSignature(string tempPdf, string signedPdf, string signatureFieldName, byte[] signedBytes)
{
using (PdfReader reader = new PdfReader(tempPdf))
{
using (FileStream os = File.OpenWrite(signedPdf))
{
PdfStamper st = PdfStamper.CreateSignature(reader, os, '\0', null, true);
PdfSignatureAppearance sap = st.SignatureAppearance;
sap.Reason = "Testing";
sap.Location = "Test";
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(250, 50, 50, 100), 1, null);
IExternalSignatureContainer external = new MyExternalSignatureContainer(signedBytes);
try
{
MakeSignature.SignExternalContainer(sap, external, 8192);
}
catch (Exception ex) { }
st.Close();
}
}
}
private class MyExternalSignatureContainer : IExternalSignatureContainer
{
private readonly byte[] signedBytes;
public MyExternalSignatureContainer(byte[] signedBytes)
{
this.signedBytes = signedBytes;
}
public byte[] Sign(Stream data)
{
return signedBytes;
}
public void ModifySigningDictionary(PdfDictionary signDic)
{
}
}
getting error..
Error during signature verification.
Error encountered while BER decoding:
Thanks...

Java: Crypto Bad Padding Exceptions

I really need some help. I am working on this assignment in school. I'm supposed to read a txt file into a list or string, and Encrypt that list of string, save it and Decrypt it back into a list of string. I was able to Encrypt it and save it, but when I try to Decrypt it back,
it give me an error message about Bad Padding.
I really don't how to fix this problem. Any help will be really good.
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.*;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class WordAnalysisMenu {
private static KeyGenerator kgen;
private static SecretKey key;
private static byte[] iv = null;
static Scanner sc = new Scanner(System.in);
private static void init(){
try {
kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
key = kgen.generateKey();
} catch (NoSuchAlgorithmException e) {
}
}
public static void main (String [] arge) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IOException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
List<String> warPeace = new ArrayList<>();
while(true) {
int choice = menu();
switch(choice) {
case 0:
break;
case 1:
//select file for reading
warPeace = readFile();
break;
case 7:
//apply the cipher and save it to a file
init();
Frame frame = new Frame();
FileDialog fileDialog = new FileDialog(frame, "", FileDialog.SAVE);
fileDialog.setVisible(true);
Path path = Paths.get(fileDialog.getDirectory() + fileDialog.getFile());
iv = ListEncrypter(warPeace, path, key);
break;
case 8:
// read the ciper file, decode, and print
init();
frame = new Frame();
fileDialog = new FileDialog(frame, "", FileDialog.LOAD);
fileDialog.setVisible(true);
Path inputFile = Paths.get(fileDialog.getDirectory() + fileDialog.getFile());
warPeace = ListDecrypter(inputFile, key, iv);
break;
case 9:
System.out.println("Good bye!");
System.exit(0);
break;
default:
break;
}
}
}
public static int menu() {
int choice = 0;
System.out.println("\nPlease make a selection: ");
System.out.println("1.\t Select a file for reading.");
System.out.println("7.\t Apply cipher & save");
System.out.println("8.\t Read encoded file");
System.out.println("9.\t Exit");
Scanner scan = new Scanner(System.in);
try {
choice = scan.nextInt();
scan.nextLine();
}
catch(InputMismatchException ime) {
System.out.println("Invalid input!");
}
return choice;
}
public static List<String> readFile() {
List<String> word = new ArrayList<String>();
Frame f = new Frame();
FileDialog saveBox = new FileDialog(f, "Reading text file", FileDialog.LOAD);
saveBox.setVisible(true);
String insName = saveBox.getFile();
String fileSavePlace = saveBox.getDirectory();
File inFile = new File(fileSavePlace + insName);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(inFile));
String line;
while (((line = in.readLine()) != null)) {
System.out.println(line);
String s = new String();
word.add(line);
}
} catch (IOException io) {
System.out.println("There Was An Error Reading The File");
} finally {
try {
in.close();
} catch (Exception e) {
e.getMessage();
}
}
return word;
}
private static byte[] ListEncrypter(List<String> content, Path outputFile, SecretKey key)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {
Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//Cipher encryptCipher = Cipher.getInstance("AES/CFB8/NoPadding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
StringBuilder sb = new StringBuilder();
content.stream().forEach(e -> sb.append(e).append(System.lineSeparator()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
cipherOutputStream.write(encryptCipher.doFinal(sb.toString().getBytes()));
//cipherOutputStream.write(sb.toString().getBytes());
cipherOutputStream.flush();
cipherOutputStream.close();
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
Files.copy(inputStream, outputFile, StandardCopyOption.REPLACE_EXISTING);
return encryptCipher.getIV();
}
private static List<String> ListDecrypter(Path inputFile, SecretKey key, byte[] iv) throws
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//Cipher decryptCipher = Cipher.getInstance("AES/CBC/CFB8NoPadding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
decryptCipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
List<String> fileContent = new ArrayList<>();
String line = null;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(inputFile));
try(CipherInputStream chipherInputStream = new CipherInputStream(new FileInputStream(inputFile.toFile()), decryptCipher);
BufferedReader br = new BufferedReader(new InputStreamReader(chipherInputStream))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
//fileContent.add(line);
}
}
return null;
}
}
This is the error message.
thread "main" java.io.IOException: javax.crypto.BadPaddingException:
Given final block not properly padded at
javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:121)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:239)

Eclipse Plugin change Language programmatically

I am trying to change the language of my RCP plugin programmatically. I had no luck so far. The Approach below is not working for me. After restart the language does not change. I populate a Menu dynamically with listet Translation files in a specific folder. The method LanguageSelectedListener.widgetSelected when a MenuItem is selected. Tried this with an exported product and also running from eclipse.
private void setMenuLanguages(Menu menu){
File dir = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + language_directory);
String[] dirList = dir.list();
String currentLocale = System.getProperty("user.language");
Locale current = new Locale(currentLocale, "", "");
Locale[] locales = new Locale[dirList.length];
LanguageSelectedListener listener = new LanguageSelectedListener();
for(int i=0; i<dirList.length; i++){
String file = dirList[i].split(".properties")[0];
String locShort;
if(file.equals("messages"))locShort = "en"; //default english
else locShort = file.split("_")[1];
locales[i] = new Locale(locShort);
MenuItem menuItem = new MenuItem(menu, SWT.RADIO, i);
menuItem.setText(locales[i].getDisplayName());
menuItem.setData("locale", locales[i]);
menuItem.addSelectionListener(listener);
if(locales[i].getLanguage().equals(current.getLanguage()))
menuItem.setSelection(true);
}
return;
}
private class LanguageSelectedListener extends SelectionAdapter{
#Override
public void widgetSelected(SelectionEvent e) {
MenuItem item = (MenuItem) e.widget;
if(!item.getSelection() || !MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Info", "Programm wird neu gestartet. Möchten Sie fortfahren?")){
item.setSelection(false);
return;
}
Locale locale = (Locale) item.getData("locale");
StringBuffer arguments = new StringBuffer();
arguments.append("${eclipse.vm}\n"); //$NON-NLS-1$
arguments.append("-nl\n").append(locale.getLanguage()).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
System.setProperty("eclipse.exitcode", Integer.toString(IApplication.EXIT_RELAUNCH)); //$NON-NLS-1$
System.getProperties().setProperty(IApplicationContext.EXIT_DATA_PROPERTY, arguments.toString());
PlatformUI.getWorkbench().restart();
}
}
so I implemented the hacky solution by manipulating the ini file of the product (not the config.ini file). Works pretty well for me.
String installLoc = Platform.getInstallLocation().getURL().getPath();
String oldIniLocation = installLoc + "decoder.ini";
String content = null;
File oldIni = null;
try {
oldIni = new File(oldIniLocation);
content = FileUtils.readFileToString(oldIni, "UTF-8");
} catch (IOException e1) {
throw new RuntimeException("reading from file failed!", e1);
}
Locale locale = (Locale) item.getData("locale");
if(content.contains("-nl")){
content = content.replaceFirst("-nl\r\n..", "-nl\r\n" + locale.getLanguage());
}
else{
StringBuilder newContent = new StringBuilder("-nl\r\n" + locale.getLanguage() +"\r\n");
content = newContent.append(content).toString();
}
File newIni = new File(installLoc + "rename.ini");
try {
FileUtils.writeStringToFile(newIni, content, "UTF-8");
} catch (IOException e1) {
throw new RuntimeException("writing to file failed!", e1);
}
oldIni.delete();
//renaming newIni by moving it
oldIni = new File(installLoc + "decoder.ini");
try {
FileUtils.moveFile(newIni, oldIni);
} catch (IOException e1) {
throw new RuntimeException("renaming/moving file failed!", e1);
}
System.setProperty("eclipse.exitcode", Integer.toString(IApplication.EXIT_RESTART)); //$NON-NLS-1$
PlatformUI.getWorkbench().restart();

Testing Intuit IPP

I would like to create some unit tests for inserting data to QuickBooks Online. I am having a problem with the authentication step:
public DataServices Authenticate(IntuitServicesType intuitDataServicesType)
{
DataServices dataServices = null;
string accessToken = HttpContext.Current.Session["accessToken"].ToString();
string accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
string companyID = HttpContext.Current.Session["realm"].ToString();
// now auth to IA
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, ConfigurationManager.AppSettings["consumerKey"].ToString(), ConfigurationManager.AppSettings["consumerSecret"].ToString());
ServiceContext context = new ServiceContext(oauthValidator, accessToken, companyID, intuitDataServicesType);
dataServices = new DataServices(context);
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext.Current.Session["DataServices"] = dataServices;
}
return dataServices;
}
In my unit test project, which has no user interface, how can I obtain an access token and an access token secret? I cannot log into Intuit from that area.
[TestMethod()]
public void AuthorizeWithHeadersTest()
{
string accessToken = ConfigurationManager.AppSettings["AccessTokenQBD"];
string accessTokenSecret = ConfigurationManager.AppSettings["AccessTokenSecretQBD"];
string consumerKey = ConfigurationManager.AppSettings["ConsumerKeyQBD"];
string consumerKeySecret = ConfigurationManager.AppSettings["ConsumerSecretQBD"];
string requestUri = "https://appcenter.intuit.com/Developer/Create";
WebRequest webRequest = WebRequest.Create(requestUri);
webRequest.Headers.Add("ContentType", "text/xml");
OAuthRequestValidator target = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerKeySecret);
target.Authorize(webRequest, string.Empty);
Assert.IsTrue(webRequest.Headers.Count > 0);
}
I'm sharing a sample standalone java code snippet. You can try the same in .net
From appcenter, you can create an app to get consumer key, consumer secret and app token.
Using apiexplorer and the above consumer key, consumer secret, you can get access tokens.
AppCenter - https://appcenter.intuit.com/
Apiexplorer - https://developer.intuit.com/apiexplorer?apiname=V2QBO
You can set all the 5 values in the standalone program(setupQBO method). It will work fine.
import java.util.ArrayList;
import java.util.List;
import com.intuit.ds.qb.PartyType;
import com.intuit.ds.qb.QBCustomer;
import com.intuit.ds.qb.QBCustomerService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import org.slf4j.Logger;
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/Customer
// JavaDocs - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
public class CodegenStubCustomerall {
static String accesstoken = "";
static String accessstokensecret = "";
static String appToken = "";
static String oauth_consumer_key = "";
static String oauth_consumer_secret = "";
static String realmID = "";
static String dataSource = "";
final PlatformSessionContext context;
public CodegenStubCustomerall(PlatformSessionContext context) {
this.context = context;
}
public void testAdd(){
try {
QBCustomer entityPojo = QBObjectFactory.getQBObject(context, QBCustomer.class);
entityPojo.setName("TestQBCustomer12345");
entityPojo.setTypeOf(PartyType.PERSON);
QBCustomerService service = QBServiceFactory.getService(context, QBCustomerService.class);
QBCustomer qbQBCustomer = service.addCustomer(context, entityPojo);
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<QBCustomer> testGetAll() {
final List<QBCustomer> entityList = new ArrayList<QBCustomer>();
try {
QBCustomerService service = QBServiceFactory.getService(context, QBCustomerService.class);
List<QBCustomer> qbCustomerList = service.findAll(context, 1,100);
for (QBCustomer each : qbCustomerList) {
entityList.add(each);
}
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return entityList;
}
public static void main(String args[]) {
PlatformSessionContext context = getPlatformContext("QBO");
CodegenStubCustomerall testObj = new CodegenStubCustomerall(context);
testObj.testGetAll();
}
public static PlatformSessionContext getPlatformContext(String dataSource) {
PlatformServiceType serviceType = null;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
setupQBO();
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret, accesstoken,
accessstokensecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
private static void setupQBO() {
System.out.println("QBO token setup");
accesstoken = "replace your tokens";
accessstokensecret = "replace your tokens";
appToken = "replace your tokens";
oauth_consumer_key = "replace your tokens";
oauth_consumer_secret = "replace your tokens";
realmID = "7123456720";
dataSource = "QBO";
}
}
For sample .net code, you can refer this link.
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/0100_ipp_.net_devkit/0299_synchronous_calls/0001_data_service_apis
Thanks

send push via urban airship using their web service (java)

I have gone through the post
The code works fine for me. i need to do this using java, i tried using the HttpURLConnection and the javax.xml.rpc.Service but no luck.
I need to know how to do the implementation using java.
Solved it.
pushClient class:
public static void main(String[] args)
{
try
{
String responseString = "";
String outputString = "";
String username = "Application Key";
String password = "Application secret";
Authenticator.setDefault(new MyAuthenticator(username,password));
URL url = new URL("https://go.urbanairship.com/api/push/");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\"APID\"]}";
byte[] buffer = new byte[postdata.length()];
buffer = postdata.getBytes("UTF8");
bout.write(buffer);
byte[] b = bout.toByteArray();
httpConn.setRequestProperty("Content-Length",String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null)
{
outputString = outputString + responseString;
}
System.out.println(outputString);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
MyAuthenticator class:
private String user;
private String passwd;
public MyAuthenticator(String user, String passwd)
{
this.user = user;
this.passwd = passwd;
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, passwd.toCharArray());
}