How to Install safari extension using setup project? - google-chrome-extension

i have a working safari extension and i able to install it manually by dragging it on safari web browser. i want to know how can i install it programmatically.
i have done this for firefox, chrome and IE.
in firefox just copy your .xpi file to this folder ("C:\Users\admin\AppData\Roaming\Mozilla\Firefox\Profiles\xxx.default\extensions") in windows 7 and your extension will get installed.
and in chrome you have to write these registry keys
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Google\Chrome\Extensions\dlilbimladfdhkfbbcbjjnbleakbogef]
"version"="3.6"
"path"="C:\\extension.crx"
but in safari when i copy my .safariextz file to this folder "C:\Users\admin\AppData\Local\Apple Computer\Safari\Extensions" than extension not get installed.
can anybody guide me how can i do this.

In the folder:
~\Users\\AppData\Local\Apple Computer\Safari\Extensions
there is a file named Extensions.plist you will also need to add an entry for your extension in this file.

Extension.plist in "~\Users\AppData\Local\Apple Computer\Safari\Extensions" folder is a binary file. for read and add an entry we can use this class.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PlistCS
{
public static class Plist
{
private static List<int> offsetTable = new List<int>();
private static List<byte> objectTable = new List<byte>();
private static int refCount;
private static int objRefSize;
private static int offsetByteSize;
private static long offsetTableOffset;
#region Public Functions
public static object readPlist(string path)
{
using (FileStream f = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return readPlist(f);
}
}
public static object readPlistSource(string source)
{
return readPlist(System.Text.Encoding.UTF8.GetBytes(source));
}
public static object readPlist(byte[] data)
{
return readPlist(new MemoryStream(data));
}
public static plistType getPlistType(Stream stream)
{
byte[] magicHeader = new byte[8];
stream.Read(magicHeader, 0, 8);
if (BitConverter.ToInt64(magicHeader, 0) == 3472403351741427810)
{
return plistType.Binary;
}
else
{
return plistType.Xml;
}
}
public static object readPlist(Stream stream, plistType type = plistType.Auto)
{
if (type == plistType.Auto)
{
type = getPlistType(stream);
stream.Seek(0, SeekOrigin.Begin);
}
if (type == plistType.Binary)
{
using (BinaryReader reader = new BinaryReader(stream))
{
byte[] data = reader.ReadBytes((int)reader.BaseStream.Length);
return readBinary(data);
}
}
else
{
using (BinaryReader reader = new BinaryReader(stream))
{
byte[] data = reader.ReadBytes((int)reader.BaseStream.Length);
return readBinary(data);
}
}
}
public static void writeBinary(object value, string path)
{
using (BinaryWriter writer = new BinaryWriter(new FileStream(path, FileMode.Create)))
{
writer.Write(writeBinary(value));
}
}
public static void writeBinary(object value, Stream stream)
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(writeBinary(value));
}
}
public static byte[] writeBinary(object value)
{
offsetTable.Clear();
objectTable.Clear();
refCount = 0;
objRefSize = 0;
offsetByteSize = 0;
offsetTableOffset = 0;
//Do not count the root node, subtract by 1
int totalRefs = countObject(value) - 1;
refCount = totalRefs;
objRefSize = RegulateNullBytes(BitConverter.GetBytes(refCount)).Length;
composeBinary(value);
writeBinaryString("bplist00", false);
offsetTableOffset = (long)objectTable.Count;
offsetTable.Add(objectTable.Count - 8);
offsetByteSize = RegulateNullBytes(BitConverter.GetBytes(offsetTable[offsetTable.Count - 1])).Length;
List<byte> offsetBytes = new List<byte>();
offsetTable.Reverse();
for (int i = 0; i < offsetTable.Count; i++)
{
offsetTable[i] = objectTable.Count - offsetTable[i];
byte[] buffer = RegulateNullBytes(BitConverter.GetBytes(offsetTable[i]), offsetByteSize);
Array.Reverse(buffer);
offsetBytes.AddRange(buffer);
}
objectTable.AddRange(offsetBytes);
objectTable.AddRange(new byte[6]);
objectTable.Add(Convert.ToByte(offsetByteSize));
objectTable.Add(Convert.ToByte(objRefSize));
var a = BitConverter.GetBytes((long)totalRefs + 1);
Array.Reverse(a);
objectTable.AddRange(a);
objectTable.AddRange(BitConverter.GetBytes((long)0));
a = BitConverter.GetBytes(offsetTableOffset);
Array.Reverse(a);
objectTable.AddRange(a);
return objectTable.ToArray();
}
#endregion
#region Private Functions
private static object readBinary(byte[] data)
{
offsetTable.Clear();
List<byte> offsetTableBytes = new List<byte>();
objectTable.Clear();
refCount = 0;
objRefSize = 0;
offsetByteSize = 0;
offsetTableOffset = 0;
List<byte> bList = new List<byte>(data);
List<byte> trailer = bList.GetRange(bList.Count - 32, 32);
parseTrailer(trailer);
objectTable = bList.GetRange(0, (int)offsetTableOffset);
offsetTableBytes = bList.GetRange((int)offsetTableOffset, bList.Count - (int)offsetTableOffset - 32);
parseOffsetTable(offsetTableBytes);
return parseBinary(0);
}
private static int countObject(object value)
{
int count = 0;
switch (value.GetType().ToString())
{
case "System.Collections.Generic.Dictionary`2[System.String,System.Object]":
Dictionary<string, object> dict = (Dictionary<string, object>)value;
foreach (string key in dict.Keys)
{
count += countObject(dict[key]);
}
count += dict.Keys.Count;
count++;
break;
case "System.Collections.Generic.List`1[System.Object]":
List<object> list = (List<object>)value;
foreach (object obj in list)
{
count += countObject(obj);
}
count++;
break;
default:
count++;
break;
}
return count;
}
private static byte[] writeBinaryDictionary(Dictionary<string, object> dictionary)
{
List<byte> buffer = new List<byte>();
List<byte> header = new List<byte>();
List<int> refs = new List<int>();
for (int i = dictionary.Count - 1; i >= 0; i--)
{
var o = new object[dictionary.Count];
dictionary.Values.CopyTo(o, 0);
composeBinary(o[i]);
offsetTable.Add(objectTable.Count);
refs.Add(refCount);
refCount--;
}
for (int i = dictionary.Count - 1; i >= 0; i--)
{
var o = new string[dictionary.Count];
dictionary.Keys.CopyTo(o, 0);
composeBinary(o[i]);//);
offsetTable.Add(objectTable.Count);
refs.Add(refCount);
refCount--;
}
if (dictionary.Count < 15)
{
header.Add(Convert.ToByte(0xD0 | Convert.ToByte(dictionary.Count)));
}
else
{
header.Add(0xD0 | 0xf);
header.AddRange(writeBinaryInteger(dictionary.Count, false));
}
foreach (int val in refs)
{
byte[] refBuffer = RegulateNullBytes(BitConverter.GetBytes(val), objRefSize);
Array.Reverse(refBuffer);
buffer.InsertRange(0, refBuffer);
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] composeBinaryArray(List<object> objects)
{
List<byte> buffer = new List<byte>();
List<byte> header = new List<byte>();
List<int> refs = new List<int>();
for (int i = objects.Count - 1; i >= 0; i--)
{
composeBinary(objects[i]);
offsetTable.Add(objectTable.Count);
refs.Add(refCount);
refCount--;
}
if (objects.Count < 15)
{
header.Add(Convert.ToByte(0xA0 | Convert.ToByte(objects.Count)));
}
else
{
header.Add(0xA0 | 0xf);
header.AddRange(writeBinaryInteger(objects.Count, false));
}
foreach (int val in refs)
{
byte[] refBuffer = RegulateNullBytes(BitConverter.GetBytes(val), objRefSize);
Array.Reverse(refBuffer);
buffer.InsertRange(0, refBuffer);
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] composeBinary(object obj)
{
byte[] value;
switch (obj.GetType().ToString())
{
case "System.Collections.Generic.Dictionary`2[System.String,System.Object]":
value = writeBinaryDictionary((Dictionary<string, object>)obj);
return value;
case "System.Collections.Generic.List`1[System.Object]":
value = composeBinaryArray((List<object>)obj);
return value;
case "System.Byte[]":
value = writeBinaryByteArray((byte[])obj);
return value;
case "System.Double":
value = writeBinaryDouble((double)obj);
return value;
case "System.Int32":
value = writeBinaryInteger((int)obj, true);
return value;
case "System.String":
value = writeBinaryString((string)obj, true);
return value;
case "System.DateTime":
value = writeBinaryDate((DateTime)obj);
return value;
case "System.Boolean":
value = writeBinaryBool((bool)obj);
return value;
default:
return new byte[0];
}
}
public static byte[] writeBinaryDate(DateTime obj)
{
List<byte> buffer = new List<byte>(RegulateNullBytes(BitConverter.GetBytes(PlistDateConverter.ConvertToAppleTimeStamp(obj)), 8));
buffer.Reverse();
buffer.Insert(0, 0x33);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
public static byte[] writeBinaryBool(bool obj)
{
List<byte> buffer = new List<byte>(new byte[1] { (bool)obj ? (byte)9 : (byte)8 });
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryInteger(int value, bool write)
{
List<byte> buffer = new List<byte>(BitConverter.GetBytes((long)value));
buffer = new List<byte>(RegulateNullBytes(buffer.ToArray()));
while (buffer.Count != Math.Pow(2, Math.Log(buffer.Count) / Math.Log(2)))
buffer.Add(0);
int header = 0x10 | (int)(Math.Log(buffer.Count) / Math.Log(2));
buffer.Reverse();
buffer.Insert(0, Convert.ToByte(header));
if (write)
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryDouble(double value)
{
List<byte> buffer = new List<byte>(RegulateNullBytes(BitConverter.GetBytes(value), 4));
while (buffer.Count != Math.Pow(2, Math.Log(buffer.Count) / Math.Log(2)))
buffer.Add(0);
int header = 0x20 | (int)(Math.Log(buffer.Count) / Math.Log(2));
buffer.Reverse();
buffer.Insert(0, Convert.ToByte(header));
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryByteArray(byte[] value)
{
List<byte> buffer = new List<byte>(value);
List<byte> header = new List<byte>();
if (value.Length < 15)
{
header.Add(Convert.ToByte(0x40 | Convert.ToByte(value.Length)));
}
else
{
header.Add(0x40 | 0xf);
header.AddRange(writeBinaryInteger(buffer.Count, false));
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryString(string value, bool head)
{
List<byte> buffer = new List<byte>();
List<byte> header = new List<byte>();
foreach (char chr in value.ToCharArray())
buffer.Add(Convert.ToByte(chr));
if (head)
{
if (value.Length < 15)
{
header.Add(Convert.ToByte(0x50 | Convert.ToByte(value.Length)));
}
else
{
header.Add(0x50 | 0xf);
header.AddRange(writeBinaryInteger(buffer.Count, false));
}
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] RegulateNullBytes(byte[] value)
{
return RegulateNullBytes(value, 1);
}
private static byte[] RegulateNullBytes(byte[] value, int minBytes)
{
Array.Reverse(value);
List<byte> bytes = new List<byte>(value);
for (int i = 0; i < bytes.Count; i++)
{
if (bytes[i] == 0 && bytes.Count > minBytes)
{
bytes.Remove(bytes[i]);
i--;
}
else
break;
}
if (bytes.Count < minBytes)
{
int dist = minBytes - bytes.Count;
for (int i = 0; i < dist; i++)
bytes.Insert(0, 0);
}
value = bytes.ToArray();
Array.Reverse(value);
return value;
}
private static void parseTrailer(List<byte> trailer)
{
offsetByteSize = BitConverter.ToInt32(RegulateNullBytes(trailer.GetRange(6, 1).ToArray(), 4), 0);
objRefSize = BitConverter.ToInt32(RegulateNullBytes(trailer.GetRange(7, 1).ToArray(), 4), 0);
byte[] refCountBytes = trailer.GetRange(12, 4).ToArray();
Array.Reverse(refCountBytes);
refCount = BitConverter.ToInt32(refCountBytes, 0);
byte[] offsetTableOffsetBytes = trailer.GetRange(24, 8).ToArray();
Array.Reverse(offsetTableOffsetBytes);
offsetTableOffset = BitConverter.ToInt64(offsetTableOffsetBytes, 0);
}
private static void parseOffsetTable(List<byte> offsetTableBytes)
{
for (int i = 0; i < offsetTableBytes.Count; i += offsetByteSize)
{
byte[] buffer = offsetTableBytes.GetRange(i, offsetByteSize).ToArray();
Array.Reverse(buffer);
offsetTable.Add(BitConverter.ToInt32(RegulateNullBytes(buffer, 4), 0));
}
}
private static object parseBinaryDictionary(int objRef)
{
Dictionary<string, object> buffer = new Dictionary<string, object>();
List<int> refs = new List<int>();
int refCount = 0;
byte dictByte = objectTable[offsetTable[objRef]];
int refStartPosition;
refCount = getCount(offsetTable[objRef], out refStartPosition);
if (refCount < 15)
refStartPosition = offsetTable[objRef] + 1;
else
refStartPosition = offsetTable[objRef] + 2 + RegulateNullBytes(BitConverter.GetBytes(refCount), 1).Length;
for (int i = refStartPosition; i < refStartPosition + refCount * 2 * objRefSize; i += objRefSize)
{
byte[] refBuffer = objectTable.GetRange(i, objRefSize).ToArray();
Array.Reverse(refBuffer);
refs.Add(BitConverter.ToInt32(RegulateNullBytes(refBuffer, 4), 0));
}
for (int i = 0; i < refCount; i++)
{
buffer.Add((string)parseBinary(refs[i]), parseBinary(refs[i + refCount]));
}
return buffer;
}
private static object parseBinaryArray(int objRef)
{
List<object> buffer = new List<object>();
List<int> refs = new List<int>();
int refCount = 0;
byte arrayByte = objectTable[offsetTable[objRef]];
int refStartPosition;
refCount = getCount(offsetTable[objRef], out refStartPosition);
if (refCount < 15)
refStartPosition = offsetTable[objRef] + 1;
else
//The following integer has a header aswell so we increase the refStartPosition by two to account for that.
refStartPosition = offsetTable[objRef] + 2 + RegulateNullBytes(BitConverter.GetBytes(refCount), 1).Length;
for (int i = refStartPosition; i < refStartPosition + refCount * objRefSize; i += objRefSize)
{
byte[] refBuffer = objectTable.GetRange(i, objRefSize).ToArray();
Array.Reverse(refBuffer);
refs.Add(BitConverter.ToInt32(RegulateNullBytes(refBuffer, 4), 0));
}
for (int i = 0; i < refCount; i++)
{
buffer.Add(parseBinary(refs[i]));
}
return buffer;
}
private static int getCount(int bytePosition, out int newBytePosition)
{
byte headerByte = objectTable[bytePosition];
byte headerByteTrail = Convert.ToByte(headerByte & 0xf);
int count;
if (headerByteTrail < 15)
{
count = headerByteTrail;
newBytePosition = bytePosition + 1;
}
else
count = (int)parseBinaryInt(bytePosition + 1, out newBytePosition);
return count;
}
private static object parseBinary(int objRef)
{
byte header = objectTable[offsetTable[objRef]];
switch (header & 0xF0)
{
case 0:
{
//If the byte is
//0 return null
//9 return true
//8 return false
return (objectTable[offsetTable[objRef]] == 0) ? (object)null : ((objectTable[offsetTable[objRef]] == 9) ? true : false);
}
case 0x10:
{
return parseBinaryInt(offsetTable[objRef]);
}
case 0x20:
{
return parseBinaryReal(offsetTable[objRef]);
}
case 0x30:
{
return parseBinaryDate(offsetTable[objRef]);
}
case 0x40:
{
return parseBinaryByteArray(offsetTable[objRef]);
}
case 0x50://String ASCII
{
return parseBinaryAsciiString(offsetTable[objRef]);
}
case 0x60://String Unicode
{
return parseBinaryUnicodeString(offsetTable[objRef]);
}
case 0xD0:
{
return parseBinaryDictionary(objRef);
}
case 0xA0:
{
return parseBinaryArray(objRef);
}
}
throw new Exception("This type is not supported");
}
public static object parseBinaryDate(int headerPosition)
{
byte[] buffer = objectTable.GetRange(headerPosition + 1, 8).ToArray();
Array.Reverse(buffer);
double appleTime = BitConverter.ToDouble(buffer, 0);
DateTime result = PlistDateConverter.ConvertFromAppleTimeStamp(appleTime);
return result;
}
private static object parseBinaryInt(int headerPosition)
{
int output;
return parseBinaryInt(headerPosition, out output);
}
private static object parseBinaryInt(int headerPosition, out int newHeaderPosition)
{
byte header = objectTable[headerPosition];
int byteCount = (int)Math.Pow(2, header & 0xf);
byte[] buffer = objectTable.GetRange(headerPosition + 1, byteCount).ToArray();
Array.Reverse(buffer);
//Add one to account for the header byte
newHeaderPosition = headerPosition + byteCount + 1;
return BitConverter.ToInt32(RegulateNullBytes(buffer, 4), 0);
}
private static object parseBinaryReal(int headerPosition)
{
byte header = objectTable[headerPosition];
int byteCount = (int)Math.Pow(2, header & 0xf);
byte[] buffer = objectTable.GetRange(headerPosition + 1, byteCount).ToArray();
Array.Reverse(buffer);
return BitConverter.ToDouble(RegulateNullBytes(buffer, 8), 0);
}
private static object parseBinaryAsciiString(int headerPosition)
{
int charStartPosition;
int charCount = getCount(headerPosition, out charStartPosition);
var buffer = objectTable.GetRange(charStartPosition, charCount);
return buffer.Count > 0 ? Encoding.ASCII.GetString(buffer.ToArray()) : string.Empty;
}
private static object parseBinaryUnicodeString(int headerPosition)
{
int charStartPosition;
int charCount = getCount(headerPosition, out charStartPosition);
charCount = charCount * 2;
byte[] buffer = new byte[charCount];
byte one, two;
for (int i = 0; i < charCount; i += 2)
{
one = objectTable.GetRange(charStartPosition + i, 1)[0];
two = objectTable.GetRange(charStartPosition + i + 1, 1)[0];
if (BitConverter.IsLittleEndian)
{
buffer[i] = two;
buffer[i + 1] = one;
}
else
{
buffer[i] = one;
buffer[i + 1] = two;
}
}
return Encoding.Unicode.GetString(buffer);
}
private static object parseBinaryByteArray(int headerPosition)
{
int byteStartPosition;
int byteCount = getCount(headerPosition, out byteStartPosition);
return objectTable.GetRange(byteStartPosition, byteCount).ToArray();
}
#endregion
}
public enum plistType
{
Auto, Binary, Xml
}
public static class PlistDateConverter
{
public static long timeDifference = 978307200;
public static long GetAppleTime(long unixTime)
{
return unixTime - timeDifference;
}
public static long GetUnixTime(long appleTime)
{
return appleTime + timeDifference;
}
public static DateTime ConvertFromAppleTimeStamp(double timestamp)
{
DateTime origin = new DateTime(2001, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
public static double ConvertToAppleTimeStamp(DateTime date)
{
DateTime begin = new DateTime(2001, 1, 1, 0, 0, 0, 0);
TimeSpan diff = date - begin;
return Math.Floor(diff.TotalSeconds);
}
}
}
and use this method in commit action of Installer.cs class to add an entry of extension Extension.plist
public void InstallSafariExt()
{
string safariExtPlist = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions\\Extensions.plist";
string safariSetupPlist = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\YourComp\\YourSoft\\Extensions.plist";
string ExtDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions";
if (!Directory.Exists(ExtDir))
{
Directory.CreateDirectory(ExtDir);
if (!File.Exists(safariExtPlist))
{
File.Copy(safariSetupPlist, safariExtPlist);
}
}
else
{
if (!File.Exists(safariExtPlist))
{
File.Copy(safariSetupPlist, safariExtPlist);
}
}
object obj = Plist.readPlist(safariExtPlist);
Dictionary<string, object> dict = (Dictionary<string, object>)obj;
Dictionary<string, object> NewExt = new Dictionary<string, object>();
NewExt.Add("Hidden Bars", new List<object>());
NewExt.Add("Added Non-Default Toolbar Items", new List<object>());
NewExt.Add("Enabled", true);
NewExt.Add("Archive File Name", "YourExtName.safariextz");
NewExt.Add("Removed Default Toolbar Items", new List<object>());
NewExt.Add("Bundle Directory Name", "YourExtName.safariextension");
List<object> listExt = (List<object>)dict["Installed Extensions"];
listExt.Add(NewExt);
Plist.writeBinary(obj, safariExtPlist);
string safariExtFile = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\YourComp\\YourSoft\\YourExtName.safariextz";
string safariInstallfolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions\\YourExtName.safariextz";
string[] safExtFiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions\\", "YourExtName*.safariextz");
for (int i = 0; i < safExtFiles.Length; i++)
{
if (File.Exists(safExtFiles[i]))
File.Delete(safExtFiles[i]);
}
File.Copy(safariExtFile, safariInstallfolder);
}

Related

Recycle View Inside Of Fragment Not Calling OnViewCreate

So basically, it's as the title says. I'm implementing a recycle view inside a fragment to create a map on one part of the screen. I need two recycle views on the page but only one isn't working. When I run the debugger in Android Studio it never reaches the override methods in the Adapter class. Below is the code, unfortunately it's a lot.
I should also mention
Number of items is caclulated and is not zero
Adapter is added to recycler view
Layout manager is added to recycler view
Why aren't any of the overriden methods being called?
Please let me know if you require further information
FRAGMENT
public class FragmentMap extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
MapData mapData;
StructureData structures;
public FragmentMap(MapData mapData, StructureData structures)
{
this.mapData = mapData;
this.structures = structures;
}
public FragmentMap() {
// Required empty public constructor
}
public static FragmentMap newInstance(String param1, String param2) {
FragmentMap fragment = new FragmentMap();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
RecyclerView rv = view.findViewById(R.id.mapRecyclerView);
SelectorAdapter myAdapter = new SelectorAdapter(structures);
MapAdapter mapAdapter = new MapAdapter(mapData);
rv.setAdapter(mapAdapter);
rv.setLayoutManager(new GridLayoutManager(
getActivity(),
MapData.HEIGHT,
GridLayoutManager.HORIZONTAL,
false));
return view;
}
}
ADAPTER
public class MapAdapter extends RecyclerView.Adapter<MapViewHolder>{
MapData mapData;
public MapAdapter(MapData mapData)
{
this.mapData = mapData;
}
#NonNull
#Override
public MapViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.grid_cell,parent,false);
MapViewHolder myViewHolder = new MapViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MapViewHolder holder, int position) {
int row = position % MapData.HEIGHT;
int col = position / MapData.HEIGHT;
MapElement mapElement = mapData.get(row, col);
holder.cellOne.setImageResource(mapElement.getNorthEast());
}
#Override
public int getItemCount() {
Log.d("TAG", "getItemCount: " + MapData.HEIGHT * MapData.WIDTH);
return MapData.HEIGHT * MapData.WIDTH;
}
}
VIEWHOLDER
public class MapViewHolder extends RecyclerView.ViewHolder {
ImageView cellOne, cellTwo, cellThree, cellFour, structure;
ConstraintLayout parent;
public MapViewHolder(#NonNull View itemView) {
super(itemView);
cellOne = itemView.findViewById(R.id.imageOne);
cellTwo = itemView.findViewById(R.id.imageTwo);
cellThree = itemView.findViewById(R.id.imageThree);
cellFour = itemView.findViewById(R.id.imageFour);
parent = itemView.findViewById(R.id.parent);
int size = parent.getMeasuredHeight() / MapData.HEIGHT + 1;
ViewGroup.LayoutParams lp = itemView.getLayoutParams();
lp.width = size;
lp.height = size;
}
}
MAPDATA
public class MapData
{
public static final int WIDTH = 30;
public static final int HEIGHT = 10;
private static final int WATER = R.drawable.ic_water;
private static final int[] GRASS = {R.drawable.ic_grass1, R.drawable.ic_grass2,
R.drawable.ic_grass3, R.drawable.ic_grass4};
private static final Random rng = new Random();
private MapElement[][] grid;
private static MapData instance = null;
public static MapData get()
{
if(instance == null)
{
instance = new MapData(generateGrid());
}
return instance;
}
private static MapElement[][] generateGrid()
{
final int HEIGHT_RANGE = 256;
final int WATER_LEVEL = 112;
final int INLAND_BIAS = 24;
final int AREA_SIZE = 1;
final int SMOOTHING_ITERATIONS = 2;
int[][] heightField = new int[HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
heightField[i][j] =
rng.nextInt(HEIGHT_RANGE)
+ INLAND_BIAS * (
Math.min(Math.min(i, j), Math.min(HEIGHT - i - 1, WIDTH - j - 1)) -
Math.min(HEIGHT, WIDTH) / 4);
}
}
int[][] newHf = new int[HEIGHT][WIDTH];
for(int s = 0; s < SMOOTHING_ITERATIONS; s++)
{
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
int areaSize = 0;
int heightSum = 0;
for(int areaI = Math.max(0, i - AREA_SIZE);
areaI < Math.min(HEIGHT, i + AREA_SIZE + 1);
areaI++)
{
for(int areaJ = Math.max(0, j - AREA_SIZE);
areaJ < Math.min(WIDTH, j + AREA_SIZE + 1);
areaJ++)
{
areaSize++;
heightSum += heightField[areaI][areaJ];
}
}
newHf[i][j] = heightSum / areaSize;
}
}
int[][] tmpHf = heightField;
heightField = newHf;
newHf = tmpHf;
}
MapElement[][] grid = new MapElement[HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
MapElement element;
if(heightField[i][j] >= WATER_LEVEL)
{
boolean waterN = (i == 0) || (heightField[i - 1][j] < WATER_LEVEL);
boolean waterE = (j == WIDTH - 1) || (heightField[i][j + 1] < WATER_LEVEL);
boolean waterS = (i == HEIGHT - 1) || (heightField[i + 1][j] < WATER_LEVEL);
boolean waterW = (j == 0) || (heightField[i][j - 1] < WATER_LEVEL);
boolean waterNW = (i == 0) || (j == 0) || (heightField[i - 1][j - 1] < WATER_LEVEL);
boolean waterNE = (i == 0) || (j == WIDTH - 1) || (heightField[i - 1][j + 1] < WATER_LEVEL);
boolean waterSW = (i == HEIGHT - 1) || (j == 0) || (heightField[i + 1][j - 1] < WATER_LEVEL);
boolean waterSE = (i == HEIGHT - 1) || (j == WIDTH - 1) || (heightField[i + 1][j + 1] < WATER_LEVEL);
boolean coast = waterN || waterE || waterS || waterW ||
waterNW || waterNE || waterSW || waterSE;
grid[i][j] = new MapElement(
!coast,
choose(waterN, waterW, waterNW,
R.drawable.ic_coast_north, R.drawable.ic_coast_west,
R.drawable.ic_coast_northwest, R.drawable.ic_coast_northwest_concave),
choose(waterN, waterE, waterNE,
R.drawable.ic_coast_north, R.drawable.ic_coast_east,
R.drawable.ic_coast_northeast, R.drawable.ic_coast_northeast_concave),
choose(waterS, waterW, waterSW,
R.drawable.ic_coast_south, R.drawable.ic_coast_west,
R.drawable.ic_coast_southwest, R.drawable.ic_coast_southwest_concave),
choose(waterS, waterE, waterSE,
R.drawable.ic_coast_south, R.drawable.ic_coast_east,
R.drawable.ic_coast_southeast, R.drawable.ic_coast_southeast_concave),
null);
}
else
{
grid[i][j] = new MapElement(
false, WATER, WATER, WATER, WATER, null);
}
}
}
return grid;
}
private static int choose(boolean nsWater, boolean ewWater, boolean diagWater,
int nsCoastId, int ewCoastId, int convexCoastId, int concaveCoastId)
{
int id;
if(nsWater)
{
if(ewWater)
{
id = convexCoastId;
}
else
{
id = nsCoastId;
}
}
else
{
if(ewWater)
{
id = ewCoastId;
}
else if(diagWater)
{
id = concaveCoastId;
}
else
{
id = GRASS[rng.nextInt(GRASS.length)];
}
}
return id;
}
protected MapData(MapElement[][] grid)
{
this.grid = grid;
}
public void regenerate()
{
this.grid = generateGrid();
}
public MapElement get(int i, int j)
{
return grid[i][j];
}
}
MAP ELEMENT
public class MapElement
{
private final boolean buildable;
private final int terrainNorthWest;
private final int terrainSouthWest;
private final int terrainNorthEast;
private final int terrainSouthEast;
private Structure structure;
public MapElement(boolean buildable, int northWest, int northEast,
int southWest, int southEast, Structure structure)
{
this.buildable = buildable;
this.terrainNorthWest = northWest;
this.terrainNorthEast = northEast;
this.terrainSouthWest = southWest;
this.terrainSouthEast = southEast;
this.structure = structure;
}
public boolean isBuildable()
{
return buildable;
}
public int getNorthWest()
{
return terrainNorthWest;
}
public int getSouthWest()
{
return terrainSouthWest;
}
public int getNorthEast()
{
return terrainNorthEast;
}
public int getSouthEast()
{
return terrainSouthEast;
}
/**
* Retrieves the structure built on this map element.
* #return The structure, or null if one is not present.
*/
public Structure getStructure()
{
return structure;
}
public void setStructure(Structure structure)
{
this.structure = structure;
}
}
You are initializing only one RecyclerView in onCreateView, if you want to have two Recyclerviews you just need to initialize second one in the same way.

Implementing Undeniable Signature Scheme : random e1 and e2 failed to compute correct d in verify protocol

First you check undeniable signature scheme verifying algorithm.
Than in that there is first step telling to chose two random x1 and x2.
But the verifying algo works sometime and sometime failed depending on two randoms. ( algo implemented in java and correctly).
For the same input if we run that algo multiple time, sometime it signature is matched and sometime not, last comparison is failed.
Plz help me. Im stuck here ( lack of math).
Actually it is an signature scheme and in paper it was confusing but now i've figure out solution.
Solution code is: let me know if you need me to explain this code.
import java.lang.*;
import java.util.*;
import java.math.*;
import java.security.MessageDigest;
import java.nio.file.*;
import java.io.*;
import java.security.*;
class UndeniableSignature {
int Q; // prime
int P; // prime of form P = 2Q + 1
BigInteger G; // Generator of Z*P
int D; // private key belongs to [2 ... Q-1]
BigInteger Y; // G^D (mod P)
int invD; // D^-1 (mod Q)
Random rand = new SecureRandom(); // uniform random generator
public int[] extendedEuclidean(int a, int b) {
if(b==0) {
int[] arr=new int[3];
arr[0] = a;
arr[1] = 1;
arr[2] = 0;
return arr;
}
int[] subResult = extendedEuclidean(b,a%b);
int[] arr=new int[3];
arr[0] = subResult[0];
arr[1] = subResult[2];
arr[2] = subResult[1] - (a/b) * subResult[2];
return arr;
}
public int secureRandom(int max) {
return rand.nextInt(max);
}
public BigInteger getGenerator(BigInteger p, BigInteger q){
BigInteger generator = BigInteger.ZERO;
BigInteger exp = p.subtract(BigInteger.ONE).divide(q);
for(int i=2;i<p.intValue()-1;i++) {
generator = BigInteger.valueOf(i);
generator = generator.modPow(exp, p);
if(!generator.equals(BigInteger.ONE)) return generator;
}
// do {
// generator = BigInteger.valueOf(this.secureRandom(p.intValue()));
// generator = generator.modPow(exp, p);
// } while(generator.equals(BigInteger.ONE));
return generator;
// BigInteger generator = BigInteger.ZERO;
// for(long i = 2; i < p.intValue()-1; i++)
// {
// generator = BigInteger.valueOf(i);
// if(generator.modPow(BigInteger.valueOf(2), p).equals(BigInteger.ONE)) continue;
// if(generator.modPow(q, p).equals(BigInteger.ONE)) continue;
// else return generator;
// }
// return generator;
}
public String readMessageFile(String filename) {
try {
return new String(Files.readAllBytes(Paths.get(filename)));
} catch(Exception ex) {
System.out.println("ERR: Can't read file.");
}
return null;
}
public int[] readSignatureFile(String filename) {
InputStream is=null;
DataInputStream dis=null;
try {
is = new FileInputStream(filename);
dis = new DataInputStream(is);
ArrayList intList = new ArrayList();
int count = 0;
while(dis.available()>0) {
intList.add(dis.readInt());
}
int[] data = new int[intList.size()];
for(int i=0;i<data.length;i++) {
data[i] = (int)intList.get(i);
}
dis.close();
is.close();
return data;
} catch(Exception ex) {
System.out.println("ERR: Can't read file.");
}
return null;
}
public static void writeSignatureFile(String filename, int[] contents) {
FileOutputStream fos=null;
DataOutputStream dos=null;
try {
fos = new FileOutputStream(filename);
dos = new DataOutputStream(fos);
for(int i=0;i<contents.length;i++) {
dos.writeInt(contents[i]);
}
dos.flush();
dos.close();
fos.close();
} catch(Exception ex) {
System.out.println("ERR: Can't write to file.");
}
}
public void keyGeneration() {
System.out.println("UNDENIABLE SIGNATURE SCHEME");
System.out.println("- KEY GENERATION");
System.out.print("\tEnter prime P (such that P=2Q+1) : ");
this.P = new Scanner(System.in).nextInt();
this.Q = (this.P - 1)/2;
System.out.println("\tPrime Q is "+this.Q+".");
this.G = this.getGenerator(BigInteger.valueOf(this.P),BigInteger.valueOf(this.Q));
System.out.println("\tGenerator G of group Z*("+this.P+") is "+this.G+".");
System.out.print("\tEnter private key D (belongs to Z*P) :");
this.D = new Scanner(System.in).nextInt();
while(this.D <= 0 || this.D >= this.P) {
System.out.println("\tInvalid private key selected, please try again.");
System.out.print("\tEnter private key D (belongs to Z*P) :");
this.D = new Scanner(System.in).nextInt();
}
this.Y = this.G.modPow(BigInteger.valueOf(this.D), BigInteger.valueOf(this.P));
System.out.println("\tG^D(mod P) = "+this.Y+".");
System.out.println("\tPublic Key [P, G, Y] is ["+this.P+", "+this.G+", "+this.Y+"].");
System.out.println("\tPrivate Key [D] is ["+this.D+"].");
int[] g = this.extendedEuclidean(this.D, this.Q);
this.invD = g[1];
if(this.invD < 0) {
this.invD = this.Q - Math.abs(this.invD);
System.out.println("\tInverse was negative.");
}
System.out.println("\tInverse of D (mod Q) is "+this.invD+".");
}
public void messageSigning(String message) {
int[] signatureBytes = new int[message.length()];
for(int i=0;i<message.length();i++) {
BigInteger m = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger s = m.pow(this.D).mod(BigInteger.valueOf(this.P));
signatureBytes[i] = s.intValue();
// System.out.println("\tchar:"+message.charAt(i)+", m:"+m+", s:"+s+", S:"+signatureBytes[i]);
}
System.out.print("\tEnter signature filename : ");
String signatureFilename = new Scanner(System.in).nextLine();
this.writeSignatureFile(signatureFilename, signatureBytes);
System.out.println("\tSignature is successfully generated.");
}
// see the condition proof for w=W for solution of problem
public boolean signatureVerification(String message, int[] signature) {
for(int i=0;i<message.length();i++) {
// rand=new Random();
// int x1 = this.secureRandom(this.Q-1);
// while(x1<=1) x1 = this.secureRandom(this.Q-1);
// int x2 = this.secureRandom(this.Q-1);
// while(x2<=1) x2 = this.secureRandom(this.Q-1);
int x1 = 38, x2 = 397;
BigInteger S = BigInteger.valueOf(signature[i]);
BigInteger s = S.pow(x1);
BigInteger y = this.Y.pow(x2);
BigInteger z = s.multiply(y).mod(BigInteger.valueOf(this.P));
BigInteger w = signerChallengeForVerification(z);
BigInteger M = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger m = M.pow(x1);
BigInteger g = this.G.pow(x2);
BigInteger mg = m.multiply(g);
BigInteger W = mg.mod(BigInteger.valueOf(this.P));
// System.out.println("\ti:"+i+", char:"+message.charAt(i)+", m:"+M+", s:"+S);
// System.out.println("\t\tz:"+z+", w:"+w+" , W:"+W);
if(!w.equals(W)) {
return false;
}
}
return true;
}
public boolean disavowalProtocol(String message, int[] signature) {
int x1 = 38, x2 = 397;
BigInteger response1 = BigInteger.ZERO;
BigInteger response2 = BigInteger.ZERO;
// verification 1
for(int i=0;i<message.length();i++) {
BigInteger S = BigInteger.valueOf(signature[i]);
BigInteger s = S.pow(x1);
BigInteger y = this.Y.pow(x2);
BigInteger z = s.multiply(y).mod(BigInteger.valueOf(this.P));
BigInteger w = signerChallengeForVerification(z);
BigInteger M = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger m = M.pow(x1);
BigInteger g = this.G.pow(x2);
BigInteger mg = m.multiply(g);
BigInteger W = mg.mod(BigInteger.valueOf(this.P));
// System.out.println("\ti:"+i+", char:"+message.charAt(i)+", m:"+M+", s:"+S);
// System.out.println("\t\tz:"+z+", w:"+w+" , W:"+W);
if(!w.equals(W)) {
response1 = w;
break;
}
}
if(response1.equals(BigInteger.ZERO)) {
return false; // signature is not forgery bcoz signature is matched
}
// verification 2
for(int i=0;i<message.length();i++) {
BigInteger S = BigInteger.valueOf(signature[i]);
BigInteger s = S.pow(x1);
BigInteger y = this.Y.pow(x2);
BigInteger z = s.multiply(y).mod(BigInteger.valueOf(this.P));
BigInteger w = signerChallengeForVerification(z);
BigInteger M = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger m = M.pow(x1);
BigInteger g = this.G.pow(x2);
BigInteger mg = m.multiply(g);
BigInteger W = mg.mod(BigInteger.valueOf(this.P));
// System.out.println("\ti:"+i+", char:"+message.charAt(i)+", m:"+M+", s:"+S);
// System.out.println("\t\tz:"+z+", w:"+w+" , W:"+W);
if(!w.equals(W)) {
response2 = w;
break;
}
}
if(response2.equals(BigInteger.ZERO)) {
return false; // signature is not forgery bcoz signature is matched
}
// forgery validation now it comes here only when one of above validation is failed
BigInteger A = response1.divide(this.G.pow(x2)).pow(x1).mod(BigInteger.valueOf(this.P));
BigInteger B = response2.divide(this.G.pow(x1)).pow(x2).mod(BigInteger.valueOf(this.P));
return A.equals(B); // signature is forgery if A == B
}
public BigInteger signerChallengeForVerification(BigInteger z) {
// System.out.println("\tchallange: "+z+", invD:"+this.invD+", d:"+(z.pow(this.invD).mod(BigInteger.valueOf(this.P))));
return z.pow(this.invD).mod(BigInteger.valueOf(this.P));
}
}
class Program {
public static void main(String[] args) {
String msgFilename, signatureFilename, message;
UndeniableSignature scheme = new UndeniableSignature();
scheme.keyGeneration();
int choice = 0;
do {
System.out.println();
System.out.println("- OPERATIONS");
System.out.println("\t1. Sign message");
System.out.println("\t2. Verify signature");
System.out.println("\t3. Disavowal protocal");
System.out.println("\t4. Exit");
System.out.print("\tChoice : ");
choice = new Scanner(System.in).nextInt();
System.out.println();
switch(choice) {
case 1:
System.out.println("- MESSAGE SIGNING");
System.out.print("\tEnter message filename : ");
msgFilename = new Scanner(System.in).nextLine();
message = new String(scheme.readMessageFile(msgFilename));
scheme.messageSigning(message);
break;
case 2:
System.out.println("- SIGNATURE VERIFICATION");
System.out.print("\tEnter message filename : ");
msgFilename = new Scanner(System.in).nextLine();
System.out.print("\tEnter signature filename : ");
signatureFilename = new Scanner(System.in).nextLine();
message = scheme.readMessageFile(msgFilename);
int[] signatureBytes = scheme.readSignatureFile(signatureFilename);
if(scheme.signatureVerification(message, signatureBytes)) {
System.out.println("\tSignature IS valid.");
} else {
System.out.println("\tSignature is NOT valid.");
}
break;
case 3:
System.out.println("- DISAVOWAL VERIFICATION");
System.out.print("\tEnter message filename : ");
msgFilename = new Scanner(System.in).nextLine();
System.out.print("\tEnter signature filename : ");
signatureFilename = new Scanner(System.in).nextLine();
message = scheme.readMessageFile(msgFilename);
signatureBytes = scheme.readSignatureFile(signatureFilename);
if(scheme.disavowalProtocol(message, signatureBytes)) {
System.out.println("\tSignature IS forgery.");
} else {
System.out.println("\tSignature is NOT forgery.");
}
break;
case 4:
System.out.println("- BYE BYE");
break;
}
} while(choice!=4);
}
}
thanks :D

How to detect window state in linux?

I need to find out if a native linux application window is maximized or minimized in a java program.
I tried using X11.XGetWindowProperty() and I get some results also, but I cant make out any useful information in it.
I am using JNA 4.2.1, Java 8 update72 on Ubuntu 14.04 LTS. Any pointers will be very helpful. Thanks in advance to all.
[Edit]
I have the code below which gives me the result I need. But the result is not same for every invocation. The atoms which are returned for the window vary within invocations. Is there any other reliable way to get the window state?
private static X11 x11 = X11.INSTANCE;
private static Display dispy = x11.XOpenDisplay(null);
public static void main(String[] args) {
try {
X11.Atom[] atoms = getAtomProperties(
bytesToInt(getProperty(X11.XA_ATOM, X11.INSTANCE.XInternAtom(dispy, "_NET_WM_STATE", false))));
boolean hidden = false;
boolean vmax = false;
boolean hmax = false;
for (int i = 0; i < atoms.length; i++) {
X11.Atom atom = atoms[i];
if (atom == null)
continue;
String atomName = X11.INSTANCE.XGetAtomName(dispy, atom);
if ("_NET_WM_STATE_HIDDEN".equals(atomName)) {
hidden = true;
} else if ("_NET_WM_STATE_MAXIMIZED_VERT".equals(atomName)) {
vmax = true;
} else if ("_NET_WM_STATE_MAXIMIZED_HORZ".equals(atomName)) {
hmax = true;
}
}
if (hidden)
System.out.println("Window minimized");
else if (vmax && hmax && !hidden)
System.out.println("Window maximized");
else
System.out.println("Window normal");
} catch (X11Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static X11.Atom[] getAtomProperties(int[] ids) {
X11.Atom[] atoms = new X11.Atom[ids.length];
for (int i = 0; i < ids.length; i++) {
if (ids[i] == 0)
continue;
atoms[i] = new X11.Atom(ids[i]);
}
return atoms;
}
private static int[] bytesToInt(byte[] prop) {
if (prop == null)
return null;
int[] res = new int[prop.length / 4];
for (int i = 0; i < res.length; i++) {
res[i] = ((prop[i * 4 + 3] & 0xff) << 24) | ((prop[i * 4 + 2] & 0xff) << 16) | ((prop[i * 4 + 1] & 0xff) << 8)
| ((prop[i * 4 + 0] & 0xff));
if (res[i] != 0)
continue;
}
return res;
}
private static byte[] getProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception {
X11.Window window = new X11.Window(73400355);
X11.AtomByReference xa_ret_type_ref = new X11.AtomByReference();
IntByReference ret_format_ref = new IntByReference();
NativeLongByReference ret_nitems_ref = new NativeLongByReference();
NativeLongByReference ret_bytes_after_ref = new NativeLongByReference();
PointerByReference ret_prop_ref = new PointerByReference();
NativeLong long_offset = new NativeLong(0);
NativeLong long_length = new NativeLong(4096 / 4);
/*
* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage):
*
* long_length = Specifies the length in 32-bit multiples of the data to be retrieved.
*/
if (x11.XGetWindowProperty(dispy, window, xa_prop_name, long_offset, long_length, false, xa_prop_type, xa_ret_type_ref,
ret_format_ref, ret_nitems_ref, ret_bytes_after_ref, ret_prop_ref) != X11.Success) {
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Cannot get " + prop_name + " property.");
}
X11.Atom xa_ret_type = xa_ret_type_ref.getValue();
Pointer ret_prop = ret_prop_ref.getValue();
if (xa_ret_type == null) {
// the specified property does not exist for the specified window
return null;
}
if (xa_ret_type == null || xa_prop_type == null || !xa_ret_type.toNative().equals(xa_prop_type.toNative())) {
x11.XFree(ret_prop);
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Invalid type of " + prop_name + " property");
}
int ret_format = ret_format_ref.getValue();
long ret_nitems = ret_nitems_ref.getValue().longValue();
// null terminate the result to make string handling easier
int nbytes;
if (ret_format == 32)
nbytes = Native.LONG_SIZE;
else if (ret_format == 16)
nbytes = Native.LONG_SIZE / 2;
else if (ret_format == 8)
nbytes = 1;
else if (ret_format == 0)
nbytes = 0;
else
throw new X11Exception("Invalid return format");
int length = Math.min((int) ret_nitems * nbytes, 4096);
byte[] ret = ret_prop.getByteArray(0, length);
x11.XFree(ret_prop);
return ret;
}

NullPointerException in working with JButtons

public class Node extends JButton {
private Node rightConnection ;
private Node downConnection ;
private Node rightNode ,downNode, leftNode ,upNode;
private ArrayList<String> buttonImages = new ArrayList<String>();
public static void connectNodes(ArrayList<Node> nodes) {
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).setRightNode((nodes.get(i).getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + 1) : null);
nodes.get(i).setDownNode((nodes.get(i).getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + Integer.parseInt(SetMap.getMapSize())) : null);
nodes.get(i).setLeftNode((nodes.get(i).getLocation().x / 150 > 0) ? nodes.get(i - 1) : null);
nodes.get(i).setUpNode((nodes.get(i).getLocation().y / 150 > 0) ? nodes.get(i - Integer.parseInt(SetMap.getMapSize())) : null);
}
}
public class SetContent {
private JPanel contentPanel;
private int imgNum;
public SetContent() {
contentPanel = new JPanel(null);
contentPanel.setLocation(1166, 0);
contentPanel.setSize(200, 768);
makeOptionNodes();
}
private void makeOptionNodes() {
MouseListener mouseListener = new DragMouseAdapter();
for (int row = 0; row < 13; row++) {
for (int col = 0; col < 2; col++) {
Node button = new Node();
button.setSize(100, 50);
button.setLocation(col * 100, row * 50);
ImageIcon img = new ImageIcon("src/com/company/" + this.imgNum++ + ".png");
button.setIcon(new ImageIcon(String.valueOf(img)));
// to remote the spacing between the image and button's borders
//button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
//button.setBackground( ... );
button.setTransferHandler(new TransferHandler("icon"));
button.addMouseListener(mouseListener);
contentPanel.add(button);
}
}
}
}
public class DragMouseAdapter extends MouseAdapter{
String name= new String();
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
name = handler.getDragImage().toString();// here is another nullpointerException
for(int i = 0 ; i< Integer.parseInt(SetMap.getMapSize()) ; i++) {
if (c.getName().equals(String.valueOf(i))) {
((Node) c).getButtonImages().add(name);
}
}
}
}
public class SetMap {
private static String mapSize;
private JPanel nodesPanel;
private ArrayList<Node> nodes;
public SetMap() {
nodes = new ArrayList<Node>();
for (Node node : nodes) {
node = new Node();
}
nodesPanel = new JPanel(null);
nodesPanel.setLocation(0, 0);
nodesPanel.setSize(1166, 768);
this.mapSize = JOptionPane.showInputDialog(null, "enter map size:");
makeMapNodes();
Node.connectNodes(this.nodes);
makeConnections();
}
private void makeMapNodes() {
for (int row = 0; row < Integer.parseInt(this.mapSize); row++) {
for (int col = 0; col < Integer.parseInt(this.mapSize); col++) {
final Node button = new Node();
button.setRightNode(null);
button.setDownNode(null);
button.setLeftNode(null);
button.setUpNode(null);
button.setRightConnection(null);
button.setDownConnection(null);
button.setTransferHandler(new TransferHandler("icon"));
button.setSize(100, 100);
button.setLocation(col * 150, row * 150);
this.nodes.add(button);
nodesPanel.add(button);
Node.setNodeName(this.nodes, this.nodes.indexOf(button));
button.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
int index = nodes.indexOf(button);
nodes.remove(button);
Node.setNodeName(nodes, index);
button.invalidate();
button.setVisible(false);
if (button.getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getRightConnection().invalidate();
button.getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getDownConnection().invalidate();
button.getDownConnection().setVisible(false);
}
if (button.getLocation().x / 150 > 0) {
button.getLeftNode().getRightConnection().invalidate();
button.getLeftNode().getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 > 0) {
button.getUpNode().getDownConnection().invalidate();
button.getUpNode().getDownConnection().setVisible(false);
}
}
});
}
}
}
private void makeConnections() {
for (Node button : this.nodes){
final Node rightConnection = new Node();
final Node downConnection = new Node();
rightConnection.setSize(50, 35);
downConnection.setSize(35, 50);
rightConnection.setLocation(button.getLocation().x + 100, button.getLocation().y + 35);
downConnection.setLocation(button.getLocation().x + 35, button.getLocation().y + 100);
button.setRightConnection(rightConnection);
button.setDownConnection(downConnection);
ImageIcon imgH = new ImageIcon("src/com/company/horizontal.png");
rightConnection.setIcon(new ImageIcon(String.valueOf(imgH)));
ImageIcon imgV = new ImageIcon("src/com/company/vertical.png");
downConnection.setContentAreaFilled(false);
downConnection.setIcon(new ImageIcon(String.valueOf(imgV)));
if(button.getLocation().x / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(rightConnection);
}
if(button.getLocation().y / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(downConnection);
}
rightConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
rightConnection.invalidate();
rightConnection.setVisible(false);
}
});
downConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
downConnection.invalidate();
downConnection.setVisible(false);
}
});
}
}
}
public class File {
public static void writeInFile(ArrayList<Node> nodes) {
try {
FileWriter fileWriter = new FileWriter("G:\\file.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("[" + SetMap.getMapSize() + "]" + "[" + SetMap.getMapSize() + "]");
bufferedWriter.newLine();
Iterator itr = nodes.iterator();
while (itr.hasNext()) {
Node node = (Node) itr.next();
if (node != null) {
bufferedWriter.write(node.getText());
bufferedWriter.newLine();
bufferedWriter.write("R" + ((node.getRightConnection() != null) ? node.getRightNode().getText() : null) + " D" + ((node.getDownConnection() != null) ? node.getDownNode().getText() : null) + " L" + ((node.getLeftNode().getRightConnection() != null) ? node.getLeftNode().getText() : null) + " U" + ((node.getUpNode().getDownConnection() != null) ? node.getUpNode().getText() : null));//here is the NullPOinterException
bufferedWriter.newLine();
bufferedWriter.write("image");
bufferedWriter.newLine();
Iterator it = node.getButtonImages().iterator();
while (it.hasNext()){
String images = (String) it.next();
bufferedWriter.write(" " + images);
}
}
}
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
public class Main {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(null);
final SetMap map = new SetMap();
SetContent options = new SetContent();
mainFrame.add(map.getNodesPanel());
mainFrame.add(options.getContentPanel());
JButton saveButton = new JButton("save");
saveButton.setSize(100, 25);
saveButton.setLocation(1050, 10);
saveButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
File.writeInFile(map.getNodes());
}
});
map.getNodesPanel().add(saveButton);
mainFrame.setVisible(true);
JOptionPane.showMessageDialog(null, "choose nodes and connections you want to remove");
}
}
I'm trying to write the changes that are made on some nodes I added in mapPanel but in the File class the line (which is commented), I get NullPointerException and also for another line in class DragMouseAdapter I get this exception again.
I've omitted some unimportant part of code. I know it's a lot to check code but I would be thankful for any simple help in this case cause I'm a real noob in programming.

Displaying null pointer excepetion on second iteration at the time of writing in excel using JXL?

I am trying to set or write the result of execute test cases using JXL in key driven framework. Also, I am able to write or set the result but only in first iteration. At the time of second iteration it shows null pointer exception. I tried but don't understand what the exact problem is?
Main Method:
public class MainClass {
private static final String BROWSER_PATH = "D:\\FF18\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\configuration\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\configuration\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
// other constants
private WebDriver driver;
private Properties properties;
/* private WebElement we; */
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws Exception {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() throws Exception {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(
testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(
testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
WritableData writableData= new WritableData(TEST_SUITE_PATH,"Login");
writableData.shSheet("Login", 5, 1, "Pass");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 2, "Fail");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 3, "N/A");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
private void handleScenario(String scenarioName) throws Exception {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH);
testScenarios.setSheetName("Login");
testScenarios.columnData();
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(
testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(
testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(
testScenarios.getCell("Value"), j);
System.out.println("FRMNameKK=" + framWork + ",Operation="
+ operation + ",Value=" + value);
handleObjects(operation, value, framWork);
}
}
private void handleObjects(String operation, String value, String framWork)
throws Exception {
System.out.println("HandleObject--> " + framWork);
ExcelHandler objectRepository = new ExcelHandler(
OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows in hadleObject=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(
objectRepository.getCell("FrameworkName"), k);
String ObjectName = objectRepository.readCell(
objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(
objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkNameV=" + frameWorkName
+ ",ObjectName=" + ObjectName + ",Locator=" + Locator);
if (framWork.equalsIgnoreCase(frameWorkName)) {
operateWebDriver(operation, Locator, value, ObjectName);
}
}
}
private void operateWebDriver(String operation, String Locator,
String value, String objectName) throws Exception {
System.out.println("Operation execution in progress");
WebElement temp = getElement(Locator, objectName);
if (operation.equalsIgnoreCase("SendKey")) {
temp.sendKeys(value);
}
Thread.sleep(1000);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if (operation.equalsIgnoreCase("Click")) {
temp.click();
}
if (operation.equalsIgnoreCase("Verify")) {
System.out.println("Verify--->" +temp);
temp.isDisplayed();
}
}
public WebElement getElement(String locator, String objectName)
throws Exception {
WebElement temp = null;
System.out.println("Locator-->" + locator);
if (locator.equalsIgnoreCase("id")) {
temp = driver.findElement(By.id(objectName));
} else if (locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
System.out.println("xpath temp ----->" + temp);
} else if (locator.equalsIgnoreCase("name")) {
temp = driver.findElement(By.name(objectName));
}
return temp;
}
}
WritableData
public class WritableData {
Workbook wbook;
WritableWorkbook wwbCopy;
String ExecutedTestCasesSheet;
WritableSheet shSheet;
public WritableData(String testSuitePath, String OBJECT_REPOSITORY_PATH) throws RowsExceededException, WriteException {
// TODO Auto-generated constructor stub
try { wbook = Workbook.getWorkbook(new File(testSuitePath));
wwbCopy= Workbook.createWorkbook(new File(testSuitePath),wbook);
System.out.println("writable workbookC-->" +wwbCopy);
shSheet=wwbCopy.getSheet("Login");
System.out.println("writable sheetC-->" +shSheet);
//shSheet = wwbCopy.createSheet("Login", 1);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception message" + e.getMessage()); e.printStackTrace(); } }
public void shSheet(String strSheetName, int iColumnNumber, int
iRowNumber, String strData) throws WriteException, IOException {
// TODO Auto-generated method stub
System.out.println("strDataCC---->>" +strData);
System.out.println("strSheetName<<>><<>><<>>" +strSheetName);
WritableSheet wshTemp = wwbCopy.getSheet(strSheetName);
shSheet=wwbCopy.getSheet("Login");
WritableFont cellFont = null;
WritableCellFormat cellFormat = null;
if (strData.equalsIgnoreCase("PASS")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.GREEN);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else if (strData.equalsIgnoreCase("FAIL")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.RED);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else { cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.BLACK);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
cellFormat.setWrap(true); }
Label labTemp = new Label(iColumnNumber, iRowNumber, strData,
cellFormat);
shSheet.addCell(labTemp);
System.out.println("writableSheet---->"+shSheet);
wwbCopy.write();
wwbCopy.close();
wbook.close();
}
}
Console:
writable sheetC-->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Pass
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Fail
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
Exception in thread "main" java.lang.NullPointerException
at jxl.write.biff.File.write(File.java:149)
at jxl.write.biff.WritableWorkbookImpl.write(WritableWorkbookImpl.java:706)
at com.chayan.af.WritableData.shSheet(WritableData.java:86)
at com.chayan.af.MainClass.handleTestSuite(MainClass.java:77)
at com.chayan.af.MainClass.main(MainClass.java:48)

Resources