#StackBounty: #java #tree Java implementation of well-separated pair decomposition

Bounty: 100

I was trying to implement the algorithm of the 3D well-separated pair decomposition WSPD using an octree.

First, I begin by implementing the class OctreeNode as follows:

public class OctreeNode {

public static final int BSW = 0;
public static final int BSE = 1;
public static final int BNW = 2;
public static final int BNE = 3;
public static final int ASW = 4;
public static final int ASE = 5;
public static final int ANW = 6;
public static final int ANE = 7;

public int level = 0; // level set to 0.
public OctreeNode[] children = null;
public OctreeNode father = null; // father is null
public Point_3 p = null; //point stored in a leaf
public Point_3 center = null; // point to define the center of the box of the node.
public double height = 0.0, width = 0.0, depth = 0.0;

Every non-leaf Node has exactly 8 children. I implement a constructor for the class which takes a list of points in 3D.

/**
 * Create the octree for storing an input point cloud.
 */
public OctreeNode(List<Point_3> points) {
    // We construct the octree only for non empty point cloud.
    assert(points.size() > 0);
    /**
     * We start by computing a box containing the point cloud.
     */
    // The minimum value of x,y,z in the point cloud.
    double minX = points.get(0).getX().doubleValue();
    double minY = points.get(0).getY().doubleValue();
    double minZ = points.get(0).getZ().doubleValue();

    // The maximum value of x,y,z in the point cloud.
    double maxX = points.get(0).getX().doubleValue();
    double maxY = points.get(0).getY().doubleValue();
    double maxZ = points.get(0).getZ().doubleValue();


    for(Point_3 point : points) {

        // update the minimum.
        if(minX > point.getX().doubleValue()) {
            minX = point.getX().doubleValue();
        }

        // update the minimum.
        if(minY > point.getY().doubleValue()) {
            minY = point.getY().doubleValue();
        }

        // update the minimum.
        if(minZ > point.getZ().doubleValue()) {
            minZ = point.getZ().doubleValue();
        }

        // update the maximum.
        if(maxX < point.getX().doubleValue()) {
            maxX = point.getX().doubleValue();
        }

        // update the maximum.
        if(maxY < point.getY().doubleValue()) {
            maxY = point.getY().doubleValue();
        }

        // update the maximum.
        if(maxZ < point.getZ().doubleValue()) {
            maxZ = point.getZ().doubleValue();
        }
    }

    this.center = new Point_3((minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2);
    this.width = 0.75*(maxX - minX);
    this.height = 0.75*(maxY - minY);
    this.depth = 0.75*(maxZ - minZ);

    for(Point_3 point : points) {
        this.add(point);
    }

}

After, I implement the add function of my class:

/**
 * @return true if the current node is a leaf.
 */
public boolean isLeaf() {
    return (this.children == null);
}
/**
 * @return true if the current node is empty.
 */
public boolean isEmpty() {
    return (this.children == null && this.p == null);
}

/**
 * @return true if the current node is single point.
 */
public boolean isSinglePoint() {
    return (this.children == null && this.p != null);
}

/**
 * @param o an Object.
 * @return true if the current node is equals to o
 */
@Override
public boolean equals(Object o) {
    OctreeNode n = (OctreeNode) o;
    return (n != null) && (this.center.equals(n.center));
}

/**
 * @return the diameter of the node : 0 if is empty or single point and the diameter of the box otherwise.
 */
public double diam() {
    if(this.isLeaf()) {
        return 0.0;
    }
    return 2*Math.sqrt(this.width*this.width
                                            + this.height*this.height
                                            + this.depth*this.depth);
}
/**
 * Check if the point is in the boundary of the OctreeNode
 * @param p a Point_3.
 * @return true if p is in the cube of the OctreeNode
 */
public boolean inBoundary(Point_3 p) {
    Vector_3 v = (Vector_3) this.center.minus(p);
    return (Math.abs(v.getX().doubleValue()) <= this.width && Math.abs(v.getY().doubleValue()) <= this.height && Math.abs(v.getZ().doubleValue()) <= this.depth);
}
/**
 * Add a node into the OctreeNode
 */

public void add(Point_3 p) {
    assert(this.center != null);
    if(!this.inBoundary(p))
        return;
    // Check if the current node is a leaf.
    if(this.isLeaf()) {
        // Check if the current node is empty.
        if(this.isEmpty()) {
            this.p = p;
            return;
        }
        else {
            // Check if the node contains the same point already.
            if(this.p.equals(p)) {
                return;
            }
            // The current node contains only one point and the new point
            // is different from the point of the current OctreeNode.
            // We create the set of children for the current OctreeNode.
            this.children = new OctreeNode[8];

            // Initialize the children.
            for(int i = 0; i < 8; i++) {
                this.children[i] = new OctreeNode();
            }

            // For all children we put the current OctreeNode as father and
            // we increment the level.
            for(OctreeNode child : this.children) {
                child.father = this;
                child.level = this.level + 1;
            }

            // We compute then the center points for every child

            Vector_3 vi = new Vector_3(this.width / 2, 0.0, 0.0);
            Vector_3 vj = new Vector_3(0.0, this.height / 2, 0.0);
            Vector_3 vk = new Vector_3(0.0, 0.0, this.depth / 2);

            this.children[BSW].center = this.center.sum(vk.opposite()).sum(vj.opposite()).sum(vi.opposite());
            this.children[BSE].center = this.center.sum(vk.opposite()).sum(vj.opposite()).sum(vi);
            this.children[BNW].center = this.center.sum(vk.opposite()).sum(vj).sum(vi.opposite());
            this.children[BNE].center = this.center.sum(vk.opposite()).sum(vj).sum(vi);
            this.children[ASW].center = this.center.sum(vk).sum(vj.opposite()).sum(vi.opposite());
            this.children[ASE].center = this.center.sum(vk).sum(vj.opposite()).sum(vi);
            this.children[ANW].center = this.center.sum(vk).sum(vj).sum(vi.opposite());
            this.children[ANE].center = this.center.sum(vk).sum(vj).sum(vi);

            // We put half of the dimensions of the cube for every child.
            for(OctreeNode child : children) {
                child.width = this.width / 2;
                child.depth = this.depth / 2;
                child.height = this.height / 2;
            }

            // Look for the child to add the point of the current OctreeNode.
            for(OctreeNode child : children) {
                if(child.inBoundary(this.p)) {
                    child.add(this.p);
                    break;
                }
            }

            // Look for the child to add the point p.
            for(OctreeNode child : children) {
                if(child.inBoundary(p)) {
                    child.add(p);
                    break;
                }
            }
            // this.p = null;
        }
    }
    else {

        // Look for the child to add the point p.
        for(OctreeNode child : children) {
            if(child.inBoundary(p)) {
                child.add(p);
                break;
            }
        }
    }
}

I also implement a function distance to compute the distance between two nodes in the Octree which is the distance between the two boxes of the nodes:

/**
 * @param o an OctreeNode.
 * @param u an OctreeNode.
 * @return the distance between the two nodes.
 */
public static double distance(OctreeNode o, OctreeNode u) {
    if(o == null || o.isEmpty() || u == null || u.isEmpty()) {
        return 0.0;
    }
    if(u.isLeaf() && o.isLeaf()) {
            return u.p.distanceFrom(o.p).doubleValue();
    }
    double x = 0.0;
    double y = 0.0;
    double z = 0.0;
    Vector_3 v;
    if(u.isLeaf()) {
        v = (Vector_3) u.p.minus(o.center);
        x = Math.min(Math.abs(v.getX().doubleValue()) - o.width, 0.0);
        y = Math.min(Math.abs(v.getX().doubleValue()) - o.height, 0.0);
        z = Math.min(Math.abs(v.getX().doubleValue()) - o.depth, 0.0);
        return Math.sqrt(x*x + y*y + z*z);
    }
    if(o.isLeaf()) {
        return distance(u, o);
    }
    v = (Vector_3) u.center.minus(o.center);
    x = Math.min(Math.abs(v.getX().doubleValue()) - o.width - u.width, 0.0);
    y = Math.min(Math.abs(v.getX().doubleValue()) - o.height - u.height, 0.0);
    z = Math.min(Math.abs(v.getX().doubleValue()) - o.depth - u.depth, 0.0);
    return Math.sqrt(x*x + y*y + z*z);
}
}

Now, I implement the class Octree representing and Octree

public class Octree {
public OctreeNode root;

/**
 * Create an octree from the array points.
 */
public Octree(Point_3[] points){
    /**
     * We use the constructor provided by the class OctreeNode to
     * construct the root.
     */
    this.root = new OctreeNode(Arrays.asList(points));
}
}

Here I have a question. Do you think my implementation is the best way to do it?

After this part I implement the well-separated pair decomposition class:

public class WellSeparatedPairDecomposition {
    class Pair<X,Y> {
    X x; Y y;
    Pair(X xx, Y yy) {
         x = xx;
         y = yy;
    }
    public X getFirst() {
         return x;
    }
    public Y getSecond() {
         return y;
    }

    @Override
    public boolean equals(Object o) {
         Pair<X,Y> p = (Pair<X,Y>) o;
         return (p!=null && p.getFirst() == x && p.getSecond() == y);
    }
}
/**
* Compute the WSPD from an octree and a threshold s.
* @param T the Octree,
* @param s threshold.
* @return the pairs of WSPD.
*/
public OctreeNode[][] wspd (Octree T, double epsilon) {
   Set<Pair<OctreeNode, OctreeNode>> H = new HashSet<Pair<OctreeNode, OctreeNode>>();

   wspd(T.root, T.root, epsilon, H);

   int n = H.size();
   OctreeNode[][] result = new OctreeNode[n][2];
   int i = 0;
   for(Pair<OctreeNode, OctreeNode> pair : H) {
     result[i][0] = pair.getFirst();
     result[i][1] = pair.getSecond();
     i++;
   }
   return result;
   }

   boolean isWS(OctreeNode u, OctreeNode v, double epsilon) {
      if(u == null || v == null || u.isEmpty() || v.isEmpty()) {
         return false;
   }
   double distance = OctreeNode.distance(u, v);
   return (u.diam() < epsilon*distance && v.diam() < epsilon*distance);
   }

void wspd(OctreeNode u, OctreeNode v, double epsilon, Set<Pair<OctreeNode, OctreeNode>> H) {
    if(u.isEmpty() || v.isEmpty() || (v.isLeaf() && u.isLeaf() && v.equals(u)))
        return;
    if(isWS(u, v, epsilon)) {
        H.add(new Pair<OctreeNode, OctreeNode>(u, v));
        return;
    }
    if(u.level > v.level) {
        OctreeNode temp = u;
        u = v;
        v = temp;
    }
    if(!u.isLeaf()) {
        for(OctreeNode uchild : u.children) {
            wspd(uchild, v, epsilon, H);
        }
     }
}
}

My implementation works without errors. However, when I tested, it is very slow and for big size tests it gives an outOfMemoryError. How can I improve this implementation?


Get this bounty!!!

#StackBounty: #java #tree Java implemetation of well separated pair decomposition

Bounty: 100

I was trying to implement the algorithm of the 3D well-separated pair decomposition WSPD using an octree.

First, I begin by implementing the class OctreeNode as following

public class OctreeNode {

public static final int BSW = 0;
public static final int BSE = 1;
public static final int BNW = 2;
public static final int BNE = 3;
public static final int ASW = 4;
public static final int ASE = 5;
public static final int ANW = 6;
public static final int ANE = 7;

public int level = 0; // level set to 0.
public OctreeNode[] children = null;
public OctreeNode father = null; // father is null
public Point_3 p = null; //point stored in a leaf
public Point_3 center = null; // point to define the center of the box of the node.
public double height = 0.0, width = 0.0, depth = 0.0;

Every non-leaf Node has exactly 8 children. I implement a constructor for the class which takes a list of points in 3D.

/**
 * Create the octree for storing an input point cloud.
 */
public OctreeNode(List<Point_3> points) {
    // We construct the octree only for non empty point cloud.
    assert(points.size() > 0);
    /**
     * We start by computing a box containing the point cloud.
     */
    // The minimum value of x,y,z in the point cloud.
    double minX = points.get(0).getX().doubleValue();
    double minY = points.get(0).getY().doubleValue();
    double minZ = points.get(0).getZ().doubleValue();

    // The maximum value of x,y,z in the point cloud.
    double maxX = points.get(0).getX().doubleValue();
    double maxY = points.get(0).getY().doubleValue();
    double maxZ = points.get(0).getZ().doubleValue();


    for(Point_3 point : points) {

        // update the minimum.
        if(minX > point.getX().doubleValue()) {
            minX = point.getX().doubleValue();
        }

        // update the minimum.
        if(minY > point.getY().doubleValue()) {
            minY = point.getY().doubleValue();
        }

        // update the minimum.
        if(minZ > point.getZ().doubleValue()) {
            minZ = point.getZ().doubleValue();
        }

        // update the maximum.
        if(maxX < point.getX().doubleValue()) {
            maxX = point.getX().doubleValue();
        }

        // update the maximum.
        if(maxY < point.getY().doubleValue()) {
            maxY = point.getY().doubleValue();
        }

        // update the maximum.
        if(maxZ < point.getZ().doubleValue()) {
            maxZ = point.getZ().doubleValue();
        }
    }

    this.center = new Point_3((minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2);
    this.width = 0.75*(maxX - minX);
    this.height = 0.75*(maxY - minY);
    this.depth = 0.75*(maxZ - minZ);

    for(Point_3 point : points) {
        this.add(point);
    }

}

After, I implement the add function of my class

/**
 * @return true if the current node is a leaf.
 */
public boolean isLeaf() {
    return (this.children == null);
}
/**
 * @return true if the current node is empty.
 */
public boolean isEmpty() {
    return (this.children == null && this.p == null);
}

/**
 * @return true if the current node is single point.
 */
public boolean isSinglePoint() {
    return (this.children == null && this.p != null);
}

/**
 * @param o an Object.
 * @return true if the current node is equals to o
 */
@Override
public boolean equals(Object o) {
    OctreeNode n = (OctreeNode) o;
    return (n != null) && (this.center.equals(n.center));
}

/**
 * @return the diameter of the node : 0 if is empty or single point and the diameter of the box otherwise.
 */
public double diam() {
    if(this.isLeaf()) {
        return 0.0;
    }
    return 2*Math.sqrt(this.width*this.width
                                            + this.height*this.height
                                            + this.depth*this.depth);
}
/**
 * Check if the point is in the boundary of the OctreeNode
 * @param p a Point_3.
 * @return true if p is in the cube of the OctreeNode
 */
public boolean inBoundary(Point_3 p) {
    Vector_3 v = (Vector_3) this.center.minus(p);
    return (Math.abs(v.getX().doubleValue()) <= this.width && Math.abs(v.getY().doubleValue()) <= this.height && Math.abs(v.getZ().doubleValue()) <= this.depth);
}
/**
 * Add a node into the OctreeNode
 */

public void add(Point_3 p) {
    assert(this.center != null);
    if(!this.inBoundary(p))
        return;
    // Check if the current node is a leaf.
    if(this.isLeaf()) {
        // Check if the current node is empty.
        if(this.isEmpty()) {
            this.p = p;
            return;
        }
        else {
            // Check if the node contains the same point already.
            if(this.p.equals(p)) {
                return;
            }
            // The current node contains only one point and the new point
            // is different from the point of the current OctreeNode.
            // We create the set of children for the current OctreeNode.
            this.children = new OctreeNode[8];

            // Initialize the children.
            for(int i = 0; i < 8; i++) {
                this.children[i] = new OctreeNode();
            }

            // For all children we put the current OctreeNode as father and
            // we increment the level.
            for(OctreeNode child : this.children) {
                child.father = this;
                child.level = this.level + 1;
            }

            // We compute then the center points for every child

            Vector_3 vi = new Vector_3(this.width / 2, 0.0, 0.0);
            Vector_3 vj = new Vector_3(0.0, this.height / 2, 0.0);
            Vector_3 vk = new Vector_3(0.0, 0.0, this.depth / 2);

            this.children[BSW].center = this.center.sum(vk.opposite()).sum(vj.opposite()).sum(vi.opposite());
            this.children[BSE].center = this.center.sum(vk.opposite()).sum(vj.opposite()).sum(vi);
            this.children[BNW].center = this.center.sum(vk.opposite()).sum(vj).sum(vi.opposite());
            this.children[BNE].center = this.center.sum(vk.opposite()).sum(vj).sum(vi);
            this.children[ASW].center = this.center.sum(vk).sum(vj.opposite()).sum(vi.opposite());
            this.children[ASE].center = this.center.sum(vk).sum(vj.opposite()).sum(vi);
            this.children[ANW].center = this.center.sum(vk).sum(vj).sum(vi.opposite());
            this.children[ANE].center = this.center.sum(vk).sum(vj).sum(vi);

            // We put half of the dimensions of the cube for every child.
            for(OctreeNode child : children) {
                child.width = this.width / 2;
                child.depth = this.depth / 2;
                child.height = this.height / 2;
            }

            // Look for the child to add the point of the current OctreeNode.
            for(OctreeNode child : children) {
                if(child.inBoundary(this.p)) {
                    child.add(this.p);
                    break;
                }
            }

            // Look for the child to add the point p.
            for(OctreeNode child : children) {
                if(child.inBoundary(p)) {
                    child.add(p);
                    break;
                }
            }
            // this.p = null;
        }
    }
    else {

        // Look for the child to add the point p.
        for(OctreeNode child : children) {
            if(child.inBoundary(p)) {
                child.add(p);
                break;
            }
        }
    }
}

I also implement a function distance to compute the distance between two nodes in the Octree which is the distance between the two boxs of the nodes.

/**
 * @param o an OctreeNode.
 * @param u an OctreeNode.
 * @return the distance between the two nodes.
 */
public static double distance(OctreeNode o, OctreeNode u) {
    if(o == null || o.isEmpty() || u == null || u.isEmpty()) {
        return 0.0;
    }
    if(u.isLeaf() && o.isLeaf()) {
            return u.p.distanceFrom(o.p).doubleValue();
    }
    double x = 0.0;
    double y = 0.0;
    double z = 0.0;
    Vector_3 v;
    if(u.isLeaf()) {
        v = (Vector_3) u.p.minus(o.center);
        x = Math.min(Math.abs(v.getX().doubleValue()) - o.width, 0.0);
        y = Math.min(Math.abs(v.getX().doubleValue()) - o.height, 0.0);
        z = Math.min(Math.abs(v.getX().doubleValue()) - o.depth, 0.0);
        return Math.sqrt(x*x + y*y + z*z);
    }
    if(o.isLeaf()) {
        return distance(u, o);
    }
    v = (Vector_3) u.center.minus(o.center);
    x = Math.min(Math.abs(v.getX().doubleValue()) - o.width - u.width, 0.0);
    y = Math.min(Math.abs(v.getX().doubleValue()) - o.height - u.height, 0.0);
    z = Math.min(Math.abs(v.getX().doubleValue()) - o.depth - u.depth, 0.0);
    return Math.sqrt(x*x + y*y + z*z);
}
}

Now, I implement the class Octree representing and Octree

public class Octree {
public OctreeNode root;

/**
 * Create an octree from the array points.
 */
public Octree(Point_3[] points){
    /**
     * We use the constructor provided by the class OctreeNode to
     * construct the root.
     */
    this.root = new OctreeNode(Arrays.asList(points));
}
}

Here I have a question. Do you think my implementation is the best way to do it?

After this part I implement the well-separated pair decomposition class

public class WellSeparatedPairDecomposition {
    class Pair<X,Y> {
    X x; Y y;
    Pair(X xx, Y yy) {
         x = xx;
         y = yy;
    }
    public X getFirst() {
         return x;
    }
    public Y getSecond() {
         return y;
    }

    @Override
    public boolean equals(Object o) {
         Pair<X,Y> p = (Pair<X,Y>) o;
         return (p!=null && p.getFirst() == x && p.getSecond() == y);
    }
}
/**
* Compute the WSPD from an octree and a threshold s.
* @param T the Octree,
* @param s threshold.
* @return the pairs of WSPD.
*/
public OctreeNode[][] wspd (Octree T, double epsilon) {
   Set<Pair<OctreeNode, OctreeNode>> H = new HashSet<Pair<OctreeNode, OctreeNode>>();

   wspd(T.root, T.root, epsilon, H);

   int n = H.size();
   OctreeNode[][] result = new OctreeNode[n][2];
   int i = 0;
   for(Pair<OctreeNode, OctreeNode> pair : H) {
     result[i][0] = pair.getFirst();
     result[i][1] = pair.getSecond();
     i++;
   }
   return result;
   }

   boolean isWS(OctreeNode u, OctreeNode v, double epsilon) {
      if(u == null || v == null || u.isEmpty() || v.isEmpty()) {
         return false;
   }
   double distance = OctreeNode.distance(u, v);
   return (u.diam() < epsilon*distance && v.diam() < epsilon*distance);
   }

void wspd(OctreeNode u, OctreeNode v, double epsilon, Set<Pair<OctreeNode, OctreeNode>> H) {
    if(u.isEmpty() || v.isEmpty() || (v.isLeaf() && u.isLeaf() && v.equals(u)))
        return;
    if(isWS(u, v, epsilon)) {
        H.add(new Pair<OctreeNode, OctreeNode>(u, v));
        return;
    }
    if(u.level > v.level) {
        OctreeNode temp = u;
        u = v;
        v = temp;
    }
    if(!u.isLeaf()) {
        for(OctreeNode uchild : u.children) {
            wspd(uchild, v, epsilon, H);
        }
     }
}
}

My implementation works without errors. However when I tested it is very slow and for big size tests it gives a outOfMemoryError. How can I improve this implemetation ?


Get this bounty!!!

#StackBounty: #java #xml #web-services #wcf #soap FSETSERVICE. can not implement web service, soap client

Bounty: 100

I am trying to make a client for this webservice, https://fsettestversion.edd.ca.gov/fsetwcfproxywebservice/fsetservice.svc

According to fset documentation above xml is an example for the request. I have tried using wcf.js, soap.js, .NET, JAVA JAX WS (wsimport), CFX, But i have not been able to make a succesfull PING call.

Does any one can give me a light here? I am getting the following responses (.NET, node js, JAVA) :

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"><s:Header><a:Action s:mustUnderstand="1">http://www.w3.org/2005/08/addressing/soap/fault</a:Action><a:RelatesTo>urn:uuid:9effd4c4-2ad4-4b13-a5d2-5b387221b3d7</a:RelatesTo></s:Header><s:Body><s:Fault><s:Code><s:Value>s:Sender</s:Value><s:Subcode><s:Value xmlns:a="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512">a:BadContextToken</s:Value></s:Subcode></s:Code><s:Reason><s:Text xml:lang="en-US">The message could not be processed. This is most likely because the action 'http://edd.ca.gov/IFsetService/Ping' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the ser

a:InvaildSecurity

In java the error shows

[main] INFO org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean - Creating Service {http://edd.ca.gov/}IFsetServiceService
from class com.hrx.fset.model.IFsetService
org.apache.cxf.binding.soap.SoapFault: An error occurred when verifying security for the message.
javax.xml.ws.soap.SOAPFaultException: An error occurred when verifying security for the message.
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)

The following are sample soap envelope based on documentation: https://edd.ca.gov/pdf_pub_ctr/de545.pdf

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
    <a:Action s:mustUnderstand="1">http://edd.ca.gov/IFsetService/Ping</a:Action>
    <a:MessageID>urn:uuid:a301683e-e0cc-4afc-95f2-68fa8d7d47b0</a:MessageID>
    <a:ReplyTo>
        <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
    </a:ReplyTo>
    <a:To s:mustUnderstand="1">https://fsettestversion.edd.ca.gov/fsetwcfproxywebservice/fsetservice.svc</a:To>
    <o:Security xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis200401-wss-wssecurity-secext-1.0.xsd" s:mustUnderstand="1">
        <u:Timestamp u:Id="_0">
            <u:Created>2016-07-07T19:53:30.188Z</u:Created>
            <u:Expires>2016-07-07T19:58:30.188Z</u:Expires>
        </u:Timestamp>
        <o:UsernameToken u:Id="uuid-c433d300-8e53-4794-9e79-97bf9946df61-19">
            <o:Username>UserName</o:Username>
            <o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-usernametoken-profile-1.0#PasswordText">Password123</o:Password>
        </o:UsernameToken>
    </o:Security>
</s:Header>
<s:Body xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Ping xmlns="http://edd.ca.gov/" />
</s:Body>

The following is the output configuration when importing as web service reference in a .net project:

<system.serviceModel>
<bindings>
    <basicHttpBinding>
        <binding name="basicHttpEndPoint" messageEncoding="Mtom">
            <security mode="TransportWithMessageCredential" />
        </binding>
    </basicHttpBinding>
    <customBinding>
        <binding name="basicHttpCustomLegacyEndPoint">
            <security defaultAlgorithmSuite="Default" authenticationMode="UserNameOverTransport" requireDerivedKeys="true" includeTimestamp="true" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
                <localClientSettings detectReplays="false" />
                <localServiceSettings detectReplays="false" />
            </security>
            <mtomMessageEncoding messageVersion="Soap11WSAddressingAugust2004" />
            <httpsTransport />
        </binding>
    </customBinding>
    <ws2007HttpBinding>
        <binding name="wsHttpBindingEndPoint" messageEncoding="Mtom">
            <security mode="TransportWithMessageCredential">
                <transport clientCredentialType="None" />
                <message clientCredentialType="UserName" />
            </security>
        </binding>
    </ws2007HttpBinding>
</bindings>
<client>
    <endpoint address="https://fsettestversion.edd.ca.gov/FSETWCFProxyWebService/FsetService.svc/wsHttp" binding="ws2007HttpBinding" bindingConfiguration="wsHttpBindingEndPoint" contract="ServiceReference1.IFsetService" name="wsHttpBindingEndPoint" />
    <endpoint address="https://fsettestversion.edd.ca.gov/FSETWCFProxyWebService/FsetService.svc" binding="customBinding" bindingConfiguration="basicHttpCustomLegacyEndPoint" contract="ServiceReference1.IFsetService" name="basicHttpCustomLegacyEndPoint" />
    <endpoint address="https://fsettestversion.edd.ca.gov/FSETWCFProxyWebService/FsetService.svc/basic" binding="basicHttpBinding" bindingConfiguration="basicHttpEndPoint" contract="ServiceReference1.IFsetService" name="basicHttpEndPoint" />
</client>

The following code is for .net (Using basicHttpBinding)

BasicHttpBinding myBinding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
        EndpointAddress ea = new
            EndpointAddress("https://fsettestversion.edd.ca.gov/FSETWCFProxyWebService/FsetService.svc/basic");


        ServiceReference1.FsetServiceClient client = new ServiceReference1.FsetServiceClient(myBinding, ea);
        client.ClientCredentials.UserName.UserName = username;
        client.ClientCredentials.UserName.Password = password;

        client.Open();

        Console.WriteLine(client.Ping());

        client.Close();

The output is:


El tipo de contenido multipart/related; type="application/xop+xml";start="http://tempuri.org/0";boundary="uuid:4cdfd7cb-0959-4b6f-9009-1abf534d8253+id=79";start-info="text/xml" del mensaje de respuesta no coincide con el tipo de contenido del enlace (text/xml; charset=utf-8). Si usa un codificador personalizado, asegúrese de que el método IsContentTypeSupported se implemente correctamente. Los primeros 591 bytes de la respuesta fueron: '
--uuid:4cdfd7cb-0959-4b6f-9009-1abf534d8253+id=79
Content-ID: http://tempuri.org/0
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"

a:InvalidSecurityAn error occurred when verifying security for the message.
--uuid:4cdfd7cb-0959-4b6f-9009-1abf534d8253+id=79--
'.

For wshttpbinding the following code:

   static void wsHttpTest1() {

        mSecurty.InitiateSSLTrust();
        WSHttpBinding binding = new WSHttpBinding();
        EndpointAddress ea = new EndpointAddress(new Uri("https://fsettestversion.edd.ca.gov/FSETWCFProxyWebService/FsetService.svc/wsHttp"));

        binding.Name = "wsHttpBindingEndPoint";
        binding.MessageEncoding = WSMessageEncoding.Text;//FaultException  when using Mtom as should be based on binding.
        binding.Security = new WSHttpSecurity();
        binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
        binding.Security.Transport = new HttpTransportSecurity();
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
        binding.Security.Message = new NonDualMessageSecurityOverHttp();
        binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
        binding.Security.Message.EstablishSecurityContext = false;

        FsetServiceClient proxy = new FsetServiceClient(binding, ea);
        proxy.ClientCredentials.UserName.UserName = username;
        proxy.ClientCredentials.UserName.Password = password;

        proxy.Open();
        String response = proxy.Ping();
        Console.WriteLine(response);
        proxy.Close();

    }

public class mSecurty
{
    public static void InitiateSSLTrust()
    {
        try
        {
            //SSL PASS
            ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback(
                    delegate { return true; }
                );
        }
        catch (Exception ex)
        {
        }
    }
}

The response shows:


El tipo de contenido multipart/related; type="application/xop+xml";start="http://tempuri.org/0";boundary="uuid:c6214f11-8f31-49ed-9108-ff0572d7a532+id=8";start-info="application/soap+xml" del mensaje de respuesta no coincide con el tipo de contenido del enlace (application/soap+xml; charset=utf-8). Si usa un codificador personalizado, asegúrese de que el método IsContentTypeSupported se implemente correctamente. Los primeros 1024 bytes de la respuesta fueron: '
--uuid:c6214f11-8f31-49ed-9108-ff0572d7a532+id=8
Content-ID: http://tempuri.org/0
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type="application/soap+xml"

http://www.w3.org/2005/08/addressing/soap/faulturn:uuid:c60805c6-579a-4333-9dec-035200e20fe2s:Sendera:BadContextTokenThe message could not be processed. This is most likely because the action 'http://edd.ca.gov/IFsetService/Ping' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the ser'.



Get this bounty!!!

#StackBounty: #java #php #encryption #aes Unable to replicate an encryption format from Java to PHP

Bounty: 50

I have the following Java code which was shared by one of an integration partner for their API encryption

    import java.nio.ByteBuffer;
    import java.security.AlgorithmParameters;
    import java.security.SecureRandom;
    import java.security.spec.KeySpec;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;

public class AES256 {

    /**
     *
     * @param word
     * @param keyString
     * @return
     * @throws Exception
     */
    public static String encrypt(String word, String keyString) throws Exception {
        byte[] ivBytes;
        //String password = "zohokeyoct2017";
        /*you can give whatever you want for password. This is for testing purpose*/
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        byte[] saltBytes = bytes;
        System.out.println("salt enc:"+saltBytes.toString());
        // Derive the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(keyString.toCharArray(), saltBytes, 65556, 256);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        //encrypting the word
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] encryptedTextBytes = cipher.doFinal(word.getBytes("UTF-8"));
        //prepend salt and vi
        byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
        System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
        System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
        System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length);
        return new Base64().encodeToString(buffer);
    }

    /**
     *
     * @param encryptedText
     * @param keyString
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText, String keyString) throws Exception {
        //String password = "zohokeyoct2017";
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //strip off the salt and iv
        ByteBuffer buffer = ByteBuffer.wrap(new Base64().decode(encryptedText));
        byte[] saltBytes = new byte[20];
        buffer.get(saltBytes, 0, saltBytes.length);
        byte[] ivBytes1 = new byte[16];

        buffer.get(ivBytes1, 0, ivBytes1.length);
        byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];

        buffer.get(encryptedTextBytes);
        // Deriving the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(keyString.toCharArray(), saltBytes, 65556, 256);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            System.out.println("Exception"+e);
        }

        return new String(decryptedTextBytes);
    }

    public static void main (String []args) throws Exception{
        String encryptedText;
        encryptedText = AES256.encrypt("106_2002005_9000000106","3264324");
        System.out.println("Encrypted Text:"+encryptedText);
        System.out.println("Decrypted Text:"+AES256.decrypt(encryptedText,"3264324"));

    }
}

And I tried couple of PHP codes which I got from stackoverflow or google. COuldnt make any of them working.

The code which I tried lately on PHP is below

class AtomAES {

    public function encrypt($data = '', $key = NULL, $salt = "") {
        if($key != NULL && $data != "" && $salt != ""){

            $method = "AES-256-CBC";

            //Converting Array to bytes
            $iv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
            $chars = array_map("chr", $iv);
            $IVbytes = join($chars);


            $salt1 = mb_convert_encoding($salt, "UTF-8"); //Encoding to UTF-8
            $key1 = mb_convert_encoding($key, "UTF-8"); //Encoding to UTF-8

            //SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
            $hash = openssl_pbkdf2($key1,$salt1,'256','65536', 'sha1'); 

            $encrypted = openssl_encrypt($data, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);

            return bin2hex($encrypted);
        }else{
            return "String to encrypt, Salt and Key is required.";
        }
    }

    public function decrypt($data="", $key = NULL, $salt = "") {
        if($key != NULL && $data != "" && $salt != ""){
            $dataEncypted = hex2bin($data);
            $method = "AES-256-CBC";

            //Converting Array to bytes
            $iv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
            $chars = array_map("chr", $iv);
            $IVbytes = join($chars);

            $salt1 = mb_convert_encoding($salt, "UTF-8");//Encoding to UTF-8
            $key1 = mb_convert_encoding($key, "UTF-8");//Encoding to UTF-8

            //SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
            $hash = openssl_pbkdf2($key1,$salt1,'256','65536', 'sha1'); 

            $decrypted = openssl_decrypt($dataEncypted, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
            return $decrypted;
        }else{

            return "Encrypted String to decrypt, Salt and Key is required.";

        }
    }

}

This is the PHP code which I wanted to try but it doesnt work as expected as per the Java code.

Encrypted Text:1HO8iuSZf41RzP/gUleEJY3zhtLJVwFMnhZiphnoG0m9ss+g93Sj5SqQg0D7OsgSvUZCeX2Ck5QPpFrPxM0FE/yFE5s=
Decrypted Text:This is a sample text
KEY: NEWENCTEST

Try decrypting the above java encrypted text using the PHP code and the key, if it works then great.

If someone can help me with this it will of a great help!

TIA!


Get this bounty!!!

#StackBounty: #java #collections #hashmap How to pass whole Object[] in HashMap for each iterative values

Bounty: 50

I have a task given as suppose there is a list of options a to z. the list options was coming as a parameter Object[] options then I had to convert the options selected from the list to 5 columns each meaning if i have data selected as data1,data2..datan then i should have as specified per hashmap( 1,data1…5; 2,data2…5 i need to concat the selected options with these columns so that it should look like selected options data for data1 as date1-col1…5 for data2 as data2..5 and the final return type is object only.


Get this bounty!!!

#StackBounty: #java #jasper-reports #dynamic-jasper DynamicJasper – How to add a subreport as columns?

Bounty: 50

Overview

  • I have a Java class which has an ArrayList that must be printed to
    the jasperReport as a subreport.

  • I’m using DynamicJasper library.

  • The example on this question has been modified so it can be reproduced. However the data is different on the real case.

Problem

The current code Ive come with, prints the subreport in another line. Its ugly. I wanted the subreport to just be a group of columns that are concatenated.

To make it clear, here’s the current resultCurrent issue

And What I want is something like this: enter image description here

Current code

public class Test_subReport {

    protected static JasperPrint jp;
    protected static JasperReport jr;
    protected static Map params = new HashMap();
    protected static DynamicReport dr;

    public static void main(String args[]) throws SQLException, ColumnBuilderException, ClassNotFoundException {

        Test_subReport t = new Test_subReport();
        t.createReport();

    }

    public void createReport() throws SQLException, ColumnBuilderException, ClassNotFoundException {

        ArrayList<Fruit> createMockDataset = createMockDataset();

        Style titleStyle = new Style();
        titleStyle.setHorizontalAlign(HorizontalAlign.CENTER);
        titleStyle.setFont(Font.ARIAL_SMALL_BOLD);

        Style dataStyle = new Style();
        dataStyle.setHorizontalAlign(HorizontalAlign.CENTER);
        dataStyle.setFont(Font.ARIAL_SMALL);
        dataStyle.setBlankWhenNull(true);

        final List items = SortUtils.sortCollection(createMockDataset, Arrays.asList(new String[]{"name", "description"}));

        FastReportBuilder drb = new FastReportBuilder();
        drb.setTemplateFile("templatePortrait.jrxml", true, true, true, true);
        drb.addColumn("name", "name", String.class.getName(), 30, dataStyle)
                .addColumn("description", "description", String.class.getName(), 50, dataStyle)
                .setTitle("Report")
                .setSubtitle("")
                .setPrintBackgroundOnOddRows(true)
                .setUseFullPageWidth(true);

        drb.addGroups(2);
        try {
            drb.addField("evaluations", List.class.getName());
            drb.addSubreportInGroupHeader(1, createSubreport("Evaluations"));
        } catch (Exception ex) {
            Logger.getLogger(Test_subReport.class.getName()).log(Level.SEVERE, null, ex);
        }

        DynamicReport dynamicReport = drb.build();

        dynamicReport.setTitleStyle(titleStyle);

        HashMap parametros = new HashMap();
        parametros.put("dataRelatorio", MyTools.getDataPorExtenso());

        doReport(dynamicReport, items, parametros);
    }

    public void doReport(final DynamicReport _report, final Collection _data, HashMap parametros) {
        try {
            JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(_data);

            JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(_report, new ClassicLayoutManager(), beanCollectionDataSource, parametros);

            JasperViewer.viewReport(jasperPrint);
        } catch (JRException ex) {
            ex.printStackTrace();
        }
    }

    private DynamicReport createHeaderSubreport(String title) throws Exception {
        FastReportBuilder rb = new FastReportBuilder();
        DynamicReport dr = rb
                .addColumn("id", "id", Integer.class.getName(), 100)
                .addColumn("score", "score", Double.class.getName(), 50)
                .setMargins(5, 5, 20, 20)
                .setUseFullPageWidth(true)
                .setWhenNoDataNoPages()
                .setTitle(title)
                .build();
        return dr;
    }

    private Subreport createSubreport(String title) throws Exception {
        SubReportBuilder srb = new SubReportBuilder();
        srb.setDynamicReport(createHeaderSubreport(title), new ClassicLayoutManager())
                .setStartInNewPage(true)
                .setDataSource(DJConstants.DATA_SOURCE_ORIGIN_FIELD, DJConstants.DATA_SOURCE_TYPE_COLLECTION, "evaluations");
        return srb.build();
    }

    public ArrayList<Fruit> createMockDataset() {
        ArrayList<Fruit> fruits = new ArrayList<>();

        Fruit f1 = new Fruit();
        f1.name = "Apple X1";
        f1.description = "Yummy yummy apple for the stackoverflow readers 1";

        Fruit f2 = new Fruit();
        f2.name = "Apple Ag";
        f2.description = "Yummy yummy apple for the stackoverflow readers 2";

        Fruit f3 = new Fruit();
        f3.name = "Apple Mn";
        f3.description = "Yummy yummy apple for the stackoverflow readers 3";

        Fruit f4 = new Fruit();
        f4.name = "Apple O2";
        f4.description = "Yummy yummy apple for the stackoverflow readers 4";

        //Evaluations for f1
        for (int i = 0; i < 4; i++) {
            Evaluation e = new Evaluation();
            e.id = i;
            e.score = Math.random() * 10;
            f1.evaluations.add(e);
        }

        //evaluations for f4
        for (int i = 0; i < 4; i++) {
            Evaluation e = new Evaluation();
            e.id = i;
            e.score = Math.random() * 10;
            f4.evaluations.add(e);
        }

        fruits.add(f1);
        fruits.add(f2);
        fruits.add(f3);
        fruits.add(f4);

        return fruits;

    }

    public class Fruit {

        public String name;
        public String description;
        public ArrayList<Evaluation> evaluations = new ArrayList<Evaluation>();

        public Fruit() {

        }

        public Fruit(String name, String description) {
            this.name = name;
            this.description = description;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public ArrayList<Evaluation> getEvaluations() {
            return evaluations;
        }

        public void setEvaluations(ArrayList<Evaluation> evaluations) {
            this.evaluations = evaluations;
        }

    }

    public class Evaluation {

        public int id;
        public double score;

        public Evaluation() {

        }

        public Evaluation(int id, double score) {
            this.id = id;
            this.score = score;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public double getScore() {
            return score;
        }

        public void setScore(double score) {
            this.score = score;
        }

    }

}


Get this bounty!!!

#StackBounty: #java #android #file #encryption Android java.io.IOException: write failed: EBADF (Bad file number)

Bounty: 50

I have read several posts about the EBADF error that does not resolve my issue. What makes my case unique is that I am trying to write to the getFilesDir, that should be writable by the application.

I am getting the EBADF error when executing the encrypt method. The file argument is created using:

new File(mContext.getFilesDir(), "file.dat")

Where is a listing of the encrypt method:

public static void encrypt(File file, String password, List<Object> objects) {

    byte[] salt = generateSalt();
    byte[] iv = generateIV();
    Cipher c = createCipher(password, salt, Cipher.ENCRYPT_MODE, iv);

    try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write(salt);
        fos.write(iv);
        try (CipherOutputStream cos = new CipherOutputStream(fos, c);
        ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            for (Object o : objects) {
                oos.writeObject(o);
            }
        }

    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Can anyone see why I am getting the exception?

Here is the exception log:

 Caused by: java.lang.RuntimeException: java.io.IOException: write failed: EBADF (Bad file number)
    at za.co.lot24media.password.util.EncryptUtil.encrypt(EncryptUtil.java:69)
    at za.co.lot24media.password.store.Store.save(Store.java:94)
    at za.co.lot24media.password.store.Store.createSamples(Store.java:179)
    at za.co.lot24media.password.store.Store.load(Store.java:76)
    at za.co.lot24media.password.activity.login.LoginAction$2.doInBackground(LoginAction.java:62)
    at za.co.lot24media.password.activity.login.LoginAction$2.doInBackground(LoginAction.java:55)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
    at java.lang.Thread.run(Thread.java:818) 
 Caused by: java.io.IOException: write failed: EBADF (Bad file number)
    at libcore.io.IoBridge.write(IoBridge.java:502)
    at java.io.FileOutputStream.write(FileOutputStream.java:186)
    at java.io.OutputStream.write(OutputStream.java:82)
    at javax.crypto.CipherOutputStream.close(CipherOutputStream.java:129)
    at za.co.lot24media.password.util.EncryptUtil.encrypt(EncryptUtil.java:64)

** EDITED **

The issue seems to be with the ObjectOutputStream writing to the CipherOutputStream. When I remove the ObjectOutputStream from the encrypt() method, the method succeeds. The code below works:

    public static void encrypt(File file, String password, StoreDataRecord storeDataRecord) {

    byte[] salt = generateSalt();
    byte[] iv = generateIV();
    Cipher c = createCipher(password, salt, Cipher.ENCRYPT_MODE, iv);

    try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write(salt);
        fos.write(iv);

        try (CipherOutputStream cos = new CipherOutputStream(fos, c)) {
            cos.write(new byte[10]);
        }

    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

I used byte[10] just to write arbitrary data to the stream.

** EDIT 2 **

The following solution also works, writing the data to a ByteArrayOutputStream first:

public static void encrypt(File file, String password, StoreDataRecord storeDataRecord) {

    byte[] salt = generateSalt();
    byte[] iv = generateIV();
    Cipher c = createCipher(password, salt, Cipher.ENCRYPT_MODE, iv);

    try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write(salt);
        fos.write(iv);

        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos);
             CipherOutputStream cos = new CipherOutputStream(fos, c)) {
            oos.writeObject(storeDataRecord.getVersion());
            oos.writeObject(storeDataRecord.getItems());
            cos.write(bos.toByteArray());
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}


Get this bounty!!!

#StackBounty: #java #spring #spring-data-jpa #spring-transactions #jta What is the default isolation level across nested transactions (…

Bounty: 50

Spring has 3 typical nested transacions propagations: REQUIRED, NEW and NESTED. Isolation level types are always described in terms of concurrent transactions. But what about nested case? What is the default visibility from inner to outer and the other way around and how does setting isolation level on either affect?

Is there perhaps any rule of thumb like ‘an outer transaction always sees changes from an inner unregarding isolation or propagation types’ or ‘an inner can only see outer’s changes when its set as read_uncommited. Or its set as required, etc..?

EDIT: I am not talking of actual sql queries, but the persistance context. I mean, if I create a resource and read it in another part of a nested transaction model, will i see the change unregardless of whether it was actually persisted? A good example is a transactional workflow that executes transactional methods that use repository.save, repository.find … etc


Get this bounty!!!

#StackBounty: #java #google-cloud-platform #bigdata #publish-subscribe #apache-beam Update singleton HashMap using Google pub/sub

Bounty: 250

I have a use case where I initialise a HashMap that contains a set of lookup data (information about the physical location etc. of IoT devices). This lookup data serves as reference data for a 2nd dataset which is a PCollection. This PCollection is a dataflow that provides the data that the IoT devices record. The dataflow from the IoT devices uses an Apache Beam pipeline that runs as a Google Dataflow utilising Google Cloud pub/sub.

When I process the PCollection (the device data), I link the Google Cloud pub/sub data to the related lookup entry in the HashMap.

I need to update the HashMap, based on a 2nd pub/sub that pushes changes to its data. Here’s how I’m getting a PCollection so far and doing a lookup using the HashMap:

HashMap -> contains pre-loaded lookup data (information about the IoT devices)

PCollection -> contains data from a pipeline dataflow (the data recorded by the IoT devices)

I’m generating a HashMap for the IoT device lookup data as a singleton:

public class MyData {

    private static final MyData instance = new MyData ();

    private MyData () {     
            HashMap myDataMap = new HashMap<String, String>();          
               ... logic to populate the map

            this.referenceData = myDataMap;

    }

    public HashMap<Integer, DeviceReference> referenceData;

    public static DeviceData getInstance(){
        return instance;
    }
}

I then use the HashMap in a different class where I’m subscribing to updates to the data (these are messages that e.g. give me new data that relates to the entities already stored in the HashMap). I’m subscribing to changes using a Google pub/sub with Apache beam:

HashMap<String, String> referenceData = MyData.getInstance().referenceData;

Pipeline pipeLine = Pipeline.create(options);           

// subscribe to changes in data

org.apache.beam.sdk.values.PCollection myDataUpdates;

myDataUpdates = pipeLine.begin()
    .apply(String.format("Subscribe to data updates"),
        PubsubIO.readStrings().fromTopic(
                String.format("myPubSubPath")));

What I want to do is to efficiently apply the data updates to the singleton HashMap (i.e. manipulate the HashMap based on my data subscription). How can I do this?

I have a limited understanding of Apache Beam and I only know how to do transforms on pipeline data to create another, separate PCollection. I think that this is the point of Beam, that it is for transforming large data sets into a different form. Is there a way of achieving what I need (updating a dataset based on a pub/sub subscription) using Apache Beam, or is there another way I can update the HashMap using pub/sub? (I can’t poll for the data as it creates too much latency and cost, I need to update the HashMap using a subscription).


The Google cloud docs show a way of directly subscribing to a Google Cloud pub/sub that isn’t linked to an Apache Beam pipeline. This is promising as a potential solution, and relies on the following Maven dependency:

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-pubsub</artifactId>
  <version>1.53.0</version>
</dependency>

I’m getting a conflict though, which is a conflict with the following Maven dependencies for Apache Beam:

<dependency>
  <groupId>com.google.cloud.dataflow</groupId>
  <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
  <version>2.5.0</version>
</dependency>

The issue is documented in a separate question here – Maven conflict in Java app with google-cloud-core-grpc dependency. From what I’m seeing it seems that it doesn’t matter which version of the google-cloud-pubsub Maven artifact I use, as from what I’ve figured out it looks like the v.2.5.0 beam dependency and below will always conflict with any current version of the google dependency.

(I’ve raised this as an issue in the Beam Jira – https://issues.apache.org/jira/browse/BEAM-6118)


I’m currently investigating side inputs and combine as a way to achieve updating of the HashMap:

https://www.programcreek.com/java-api-examples/?api=org.apache.beam.sdk.transforms.Combine

The example shows a way that .getSideInputsMap() can be applied to a payload. I’m wondering if I can apply this somehow to my subscription to the lookup data changes. If I get a PCollection like this, I can’t chain on a .getSideInputsMap()

deviceReferenceDataUpdates = pipeLine.begin()
    .apply("Get changes to the IoT device lookup data"),
         PubsubIO.readMessages().fromTopic("IoT device lookup data")).


Get this bounty!!!

#StackBounty: #java #android #firebase #firebase-in-app-messaging Issue in adding Firebase In-App Messaging

Bounty: 200

I had been trying to add Firebase in-app messaging into our android project. It builds successfully but when i run the app in emulator/device it throws the following error.

com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /Users/gowthamraj/.gradle/caches/modules-2/files-2.1/com.google.guava/guava/20.0/89507701249388e1ed5ddcf8c41f4ce1be7831ef/guava-20.0.jar
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
    at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
    at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)
    at com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:146)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:405)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
    at sun.reflect.GeneratedMethodAccessor1162.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:256)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:249)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:238)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:663)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:597)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:59)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:130)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:46)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:210)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:140)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:115)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
    at org.gradle.tooling.internal.provider.runner.ClientProvidedBuildActionRunner.run(ClientProvidedBuildActionRunner.java:62)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:49)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at ...org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.
    at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:124)
    at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:101)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:895)
    ... 6 more
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
    at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:65)
    at com.android.tools.r8.utils.ExceptionUtils.withD8CompilationHandler(ExceptionUtils.java:43)
    at com.android.tools.r8.D8.run(D8.java:90)
    at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:99)
    ... 7 more
Caused by: com.android.tools.r8.utils.AbortException: Error: Type com.google.common.collect.MapMakerInternalMap$WeakValueReference is referenced as an interface from `com.google.common.collect.MapMakerInternalMap$WeakValueReferenceImpl`.
    at com.android.tools.r8.utils.Reporter.failIfPendingErrors(Reporter.java:116)
    at com.android.tools.r8.utils.Reporter.fatalError(Reporter.java:74)
    at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:59)
    ... 10 more

AGPBI: {"kind":"warning","text":"InnerClass annotations are missing corresponding EnclosingMember annotations. Such InnerClass annotations are ignored.","sources":[{}],"tool":"D8"}
:app:transformClassesWithDexBuilderForDebug FAILED
:app:buildInfoGeneratorDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /Users/gowthamraj/.gradle/caches/modules-2/files-2.1/com.google.guava/guava/20.0/89507701249388e1ed5ddcf8c41f4ce1be7831ef/guava-20.0.jar

BUILD FAILED in 28s

This is my build.gradle file

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
        mavenCentral()
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.25.4'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'


repositories {
    maven { url 'https://maven.fabric.io/public' }
    jcenter()

}

android {
    buildToolsVersion "28.0.3"
    signingConfigs {
        signingConfigs {
            keyAlias 'betaKey'
            keyPassword 'password'
            storeFile file('./signing/app-beta.jks')
            storePassword 'password'
        }
    }
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.pulsedin.android"
        minSdkVersion 16
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 8
        versionName "1.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [appPackageName: "${applicationId}"]
        buildConfigField("boolean", "logging_enabled", "${log_enabled}")
        buildConfigField("String", "log_prefix", ""${log_prefix}"")
        buildConfigField("String", "client_id", "${client_id}")
        buildConfigField("String", "client_secret", "${client_secret}")
        buildConfigField("String", "grant_type", "${grant_type}")
        buildConfigField("String", "scope_institution", "${scope_institution}")
        buildConfigField("String", "scope_physician", "${scope_physician}")
        buildConfigField("String", "scope_public", "${scope_public}")
        buildConfigField("String", "refresh_token_grant_type", "${refresh_token_grant_type}")
    }
    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            applicationIdSuffix ".debug"
            resValue("string", "app_name", "${app_name_debug}")
            buildConfigField("String", "app_name", ""${app_name_debug}"")
            buildConfigField("String", "api_host_name", "${dev_api_host_name}")
            buildConfigField("String", "api_host_namev2", "${dev_api_host_namev2}")
        }
        beta {
            debuggable false
            minifyEnabled false
            applicationIdSuffix ".beta"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue("string", "app_name", "${app_name_beta}")
            buildConfigField("String", "app_name", ""${app_name_beta}"")
            buildConfigField("String", "api_host_name", "${beta_api_host_name}")
            buildConfigField("String", "api_host_namev2", "${beta_api_host_namev2}")
            // Added because library modules
            // does not have beta, gamma build type
            matchingFallbacks = ['debug', 'gamma', 'release']
            signingConfig signingConfigs.signingConfigs
        }
        gamma {
            debuggable false
            minifyEnabled false
            applicationIdSuffix ".gamma"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue("string", "app_name", "${app_name_gamma}")
            buildConfigField("String", "app_name", ""${app_name_gamma}"")
            buildConfigField("String", "api_host_name", "${gamma_api_host_name}")
            buildConfigField("String", "api_host_namev2", "${gamma_api_host_namev2}")
            // Added because library modules
            // does not have beta, gamma build type
            matchingFallbacks = ['debug', 'beta', 'release']
        }
        release {
            debuggable false
            minifyEnabled true
            applicationIdSuffix ".release"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue("string", "app_name", "${app_name_release}")
            buildConfigField("String", "app_name", ""${app_name_release}"")
            buildConfigField("boolean", "logging_enabled", "${log_disabled}")
            buildConfigField("String", "api_host_name", "${production_api_host_name}")
            buildConfigField("String", "api_host_namev2", "${production_api_host_namev2}")
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    lintOptions {
        checkReleaseBuilds false
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:${android_support_lib_version}"
    implementation "com.android.support:support-v4:${android_support_lib_version}"
    implementation "com.android.support:recyclerview-v7:${android_support_lib_version}"
    implementation "com.android.support:cardview-v7:${android_support_lib_version}"
    implementation "com.android.support:design:${android_support_lib_version}"
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    configurations.all {
        exclude group: 'com.android.support', module: 'support-v13'
    }
    implementation('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }

    // Youtube player
    implementation files('libs/YouTubeAndroidPlayerApi.jar')

    // Matisse - image, video picker
    implementation 'com.zhihu.android:matisse:0.5.1'

    // Glide
    implementation 'com.github.bumptech.glide:glide:4.7.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'

    // Butterknife
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

    // Nucleus
    implementation 'info.android15.nucleus5:nucleus:7.0.0'
    implementation 'info.android15.nucleus5:nucleus-support-v4:7.0.0'
    implementation 'info.android15.nucleus5:nucleus-support-v7:7.0.0'

    // RxJava2 and RxAndroid
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'

    // Because RxAndroid releases are few and far between, it is recommended you also

    // explicitly depend on RxJava's latest version for bug fixes and new features.
    implementation 'io.reactivex.rxjava2:rxjava:2.1.14'

    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'

    // Retrofit - RxJava call adapter
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

    // Retrofit gson converter
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

    // Okhttp logging interceptor
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'

    // Easy Permissions
    implementation 'pub.devrel:easypermissions:1.3.0'

    // Photo View - Image zoom
    implementation 'com.github.chrisbanes:PhotoView:2.1.3'

    // Otto - Event Bus
    implementation 'com.squareup:otto:1.3.8'

    // Joda time
    implementation 'joda-time:joda-time:2.9.9'

    // Picasso - Image loading
    implementation 'com.squareup.picasso:picasso:2.71828'

    // Apache commons - Text
    implementation 'org.apache.commons:commons-text:1.4'

    // Multidex
    implementation 'com.android.support:multidex:1.0.3'

    // Facebook SDK
    implementation 'com.facebook.android:facebook-android-sdk:4.22.0'

    // Firebase messaging
    implementation 'com.google.firebase:firebase-messaging:17.3.4'

    // Google play services
    implementation 'com.google.android.gms:play-services-maps:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'

    // Google People API
    implementation 'com.google.apis:google-api-services-people:v1-rev2-1.21.0'

    // File upload service
    implementation 'net.gotev:uploadservice:3.4.2'
    implementation 'net.gotev:hostmonitor:2.0@aar'

    // Jsoup - HTML Parsing
    implementation 'org.jsoup:jsoup:1.10.2'

    // Exo player - For video playing
    implementation 'com.google.android.exoplayer:exoplayer:2.7.0'

    // Image crop,rotate library
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
    //Get pdf Path
    implementation 'com.nbsp:library:1.8'

    // MultiType-FilePicker
    implementation 'com.vincent.filepicker:MultiTypeFilePicker:1.0.8'
    // Local Library modules
    implementation project(':text-editor')
    implementation project(':linkedin-sdk')
    implementation project(':mentions')

    // Add the In-App Messaging dependency:
    implementation 'com.google.firebase:firebase-inappmessaging-display:17.0.4'

    // Check that your Firebase dependency is up-to-date:
    implementation 'com.google.firebase:firebase-core:16.0.5'
}

//Firebase
apply plugin: 'com.google.gms.google-services'

Project level Gradle File:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        // FCM
        classpath 'com.google.gms:google-services:4.0.1'
    }
}



allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://repo.adobe.com/nexus/content/repositories/releases/'
        }
        maven {
            url 'http://maven.localytics.com/public'
        }
        maven {
            url 'https://jitpack.io'
        }
        maven {
            url  "http://dl.bintray.com/lukaville/maven"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

task indexAssets {
    description 'Index Build Variant assets for faster lookup by AssetManager'

    ext.assetsSrcDir = file("${projectDir}/src/main/assets")

    inputs.dir assetsSrcDir

    doLast {
        android.applicationVariants.each { target ->
            // create index
            def contents = ""
            def tree = fileTree(dir: "${ext.assetsSrcDir}", include: ['**/*.ttf'], exclude: ['**/.svn/**', '*.index'])
            // use this instead if you have assets folders in each flavor:
            // def tree = fileTree(dir: "${ext.variantPath}", exclude: ['**/.svn/**', '*.index'])
            tree.visit { fileDetails ->
                contents += "${fileDetails.relativePath}" + "n"
            }

            // create index file
            def assetIndexFile = new File("${ext.assetsSrcDir}/assets.index")
            assetIndexFile.write contents
        }
    }
}

indexAssets.dependsOn {
    tasks.matching { task -> task.name.startsWith('merge') && task.name.endsWith('Assets') }
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn indexAssets
}


Get this bounty!!!