#StackBounty: #java #sql #hibernate #jpa Hibernate CompositeUserType that is comparible in JPA-QL (or HQL) query

Bounty: 50

I’ve created a custom type for Hibernate to store an OffsetDateTime‘s timestamp and offset (because the default JPA 2.2 / Hibernate 5.2 with java 8 support implementation loses the offset information):

public class OffsetDateTimeHibernateType implements CompositeUserType {

    @Override
    public Class returnedClass() {
        return OffsetDateTime.class;
    }

    @Override
    public String[] getPropertyNames() {
        return new String[] {"dateTime", "zoneOffset"};
    }

    @Override
    public Type[] getPropertyTypes() {
        // Not sure if we should use LocalDateTimeType.INSTANCE instead of TIMESTAMP
        return new Type[]{StandardBasicTypes.TIMESTAMP, StandardBasicTypes.INTEGER};
    }

    @Override
    public Object getPropertyValue(Object o, int propertyIndex) {
        if (o == null) {
            return null;
        }
        OffsetDateTime offsetDateTime = (OffsetDateTime) o;
        switch (propertyIndex) {
            case 0:
                return Timestamp.valueOf(offsetDateTime.toLocalDateTime());
            case 1:
                return offsetDateTime.getOffset().getTotalSeconds();
            default:
                throw new IllegalArgumentException("The propertyIndex (" + propertyIndex
                        + ") must be 0 or 1.");
        }
    }

    @Override
    public OffsetDateTime nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
            throws SQLException {
        if (resultSet == null) {
            return null;
        }
        Timestamp timestamp = (Timestamp) StandardBasicTypes.TIMESTAMP.nullSafeGet(resultSet, names[0], session, owner);
        if (timestamp == null) {
            throw new IllegalStateException("The timestamp (" + timestamp + ") for an "
                    + OffsetDateTime.class.getSimpleName() + "cannot be null.");
        }
        LocalDateTime localDateTime = timestamp.toLocalDateTime();
        Integer zoneOffsetSeconds = (Integer) StandardBasicTypes.INTEGER.nullSafeGet(resultSet, names[1], session, owner);
        if (zoneOffsetSeconds == null) {
            throw new IllegalStateException("The zoneOffsetSeconds (" + zoneOffsetSeconds + ") for an "
                    + OffsetDateTime.class.getSimpleName() + "cannot be null.");
        }
        return OffsetDateTime.of(localDateTime, ZoneOffset.ofTotalSeconds(zoneOffsetSeconds));
    }

    @Override
    public void nullSafeSet(PreparedStatement statement, Object value, int parameterIndex, SessionImplementor session)
            throws SQLException {
        if (value == null) {
            statement.setNull(parameterIndex, StandardBasicTypes.TIMESTAMP.sqlType());
            statement.setNull(parameterIndex, StandardBasicTypes.INTEGER.sqlType());
            return;
        }
        OffsetDateTime offsetDateTime = (OffsetDateTime) value;
        statement.setTimestamp(parameterIndex, Timestamp.valueOf(offsetDateTime.toLocalDateTime()));
        statement.setInt(parameterIndex, offsetDateTime.getOffset().getTotalSeconds());
    }

    // ************************************************************************
    // Mutable related methods
    // ************************************************************************

    @Override
    public boolean isMutable() {
        return false;
    }

    @Override
    public Object deepCopy(Object value) {
        return value; // OffsetDateTime is immutable
    }

    @Override
    public Object replace(Object original, Object target, SessionImplementor session, Object owner) {
        return original; // OffsetDateTime is immutable
    }

    @Override
    public void setPropertyValue(Object component, int property, Object value) {
        throw new UnsupportedOperationException("A OffsetDateTime is immutable.");
    }

    // ************************************************************************
    // Other methods
    // ************************************************************************

    @Override
    public boolean equals(Object a, Object b) {
        if (a == b) {
            return true;
        } else if (a == null || b == null) {
            return false;
        }
        return a.equals(b);
    }

    @Override
    public int hashCode(Object o) {
        if (o == null) {
            return 0;
        }
        return o.hashCode();
    }

    @Override
    public Serializable disassemble(Object value, SessionImplementor session) {
        return (Serializable) value;
    }

    @Override
    public Object assemble(Serializable cached, SessionImplementor session, Object owner) {
        return cached;
    }

}

Now, I want to be able to compare it, so this JPA-QL query works:

       @NamedQuery(name = "Shift.myQuery",
                   query = "select sa from Shift sa" +
                           " where sa.endDateTime >= :startDateTime" +
                           " and sa.startDateTime < :endDateTime")

on this model:

@Entity
public class Shift {

    @Type(type = "...OffsetDateTimeHibernateType")
    @Columns(columns = {@Column(name = "startDateTime"), @Column(name="startDateTimeOffset")})
    private OffsetDateTime startDateTime;
    @Type(type = "...OffsetDateTimeHibernateType")
    @Columns(columns = {@Column(name = "endDateTime"), @Column(name="endDateTimeOffset")})
    private OffsetDateTime endDateTime;

    ...

}

But that fails with:

HHH000177: Error in named query: Shift.myQuery: org.hibernate.hql.internal.ast.QuerySyntaxException: >= operator not supported on composite types. [select sa from org.optaplanner.openshift.employeerostering.shared.shift.Shift sa where sa.endDateTime >= :startDateTime and sa.startDateTime < :endDateTime]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
    at org.hibernate.internal.NamedQueryRepository.checkNamedQueries(NamedQueryRepository.java:155)
    at org.hibernate.internal.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:796)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:492)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:422)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:880)

How can I make my CustomUserType comparable?


Get this bounty!!!

#StackBounty: #java #android #c++ #video #h.264 How to play raw NAL units in Andoid exoplayer?

Bounty: 50

I know that exoplayer has support for RTSP, but I need c++ code that works on players from lots of OSs, so I need to parse the RTP packet in C++ to NAL units before passing to exoplayer

I found a way to decode RTP packets using live555 and extract its NAL units. According to ExoPlayer’s documentation:

Components common to all ExoPlayer implementations are:

A MediaSource that defines the media to be played, loads the media, and from which the loaded media can be read.

A MediaSource is
injected via ExoPlayer.prepare at the start of playback. …

So I need a custom MediaSource that can extract NAL units from my C++ code.

At the class reference for MediaSource we can see that there are already some MediaSources available. I though maybe SmoothStreaming MediaSource could work but there’s no description of what it does exactly and in its constructor I have to provide an Uri or an SsManifest (what).

I can see that there exists a NAL unit utility in this library so maybe things are already half done

So how to build or use an already available MediaSource to read NAL units for ExoPlayer to play?

As an additinal, how would you pass the NAL units from C++ to Java? In the code I found it’s simply storing them in a C++ buffer. Should I read this buffer in Java somehow?


Get this bounty!!!

#StackBounty: #java #proxy #google-apps #http-proxy Need a Java Class/tool/utility which can allow to do HTTP REST Call data manipulati…

Bounty: 50

We have very limited licences, So is it possible that I can fetch same data from Cloud applications via some utility/proxies which can do little data manipulation for us before storing it into our application server.

Consider the usecase, I have only 100 users on GoogleApps and I want to load 10K users

  1. Now, I want a man in middle i.e. proxy which can basically cheat our application server that there are N number(e.g. 10K) of users present on Cloud system.

  2. As my Application Server believes that there are still many users present on Cloud system, it will keep generating request for next chunk of user data until we don’t cross number N

  3. It will also manipulate the data that is being sent to my application server with incremental number e.g. User1, User2,…, User100, and from next chunk User101,…, User100000 etc.

I found few HTTP proxy java projects here, can anybody help me to implement above mentioned scenarios and which one I should go for from below

  1. https://github.com/adamfisk/LittleProxy
  2. https://github.com/geosolutions-it/http-proxy

  3. https://github.com/stefano-lupo/Java-Proxy-Server


Get this bounty!!!

#StackBounty: #java #grails #groovy #closures #criteria Refactor closure criteria to fix maximum number of expressions in a list is 1000

Bounty: 50

I’ve found the following piece of code in an application I have to maintain

 def addCriteriaClosure = { criteriaList ->
   criteriaList.inList('id', paketInstance.dateien.id)
 }
 def criteria = Datei.createCriteria()
 def result = criteria.list() {
   addCriteriaClosure.call(criteria)
 }

Sadly, this call results in the following error:

java.sql.SQLSyntaxErrorException: ORA-01795: maximum number of expressions in a list is 1000

Fact is that paketInstance.dateien contains more then 1000 rows / items.
To avoid this error I’ve tried the following approach:

def addCriteriaClosure = { criteriaList ->
  paketInstance.dateien.asList().collate(999).each {
    criteriaList.inList('id', paketInstance.dateien.asList().collate(999).id)
  }
}

but this results in this error:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Long

I know that the solution is to use the collate(999) operation, but I don’t know how to combine it with the initial approach to get the expected result.

Edit #1

Unfortunatly I can not edit this part of the implementation:

 def criteria = [Type].createCriteria()
 def result = criteria.list() {
   addCriteriaClosure.call(criteria)
 }

Where the concrete type gets passed in to the method.
I only can edit the definition of the addCriteriaClosure
For example:

 def addCriteriaClosure = { criteriaList ->
   criteriaList.inList('id', paketInstance.dateien.id)
 }


Get this bounty!!!

#StackBounty: #java #parsing #xml XML Parser written in Java

Bounty: 50

Accepts a String (or a char array) as an input and stores the data in a tree structure.

For example, given the input:

<foo>
    <bar>baz</bar>
    <qux fox="jump"/>
</foo>

Output will be:

XMLElement{elementName='foo', 
    children=[XMLElement{elementName='bar', elementValue='baz'}, 
              XMLElement{elementName='qux', attributes=[ElementAttribute{name='fox', value='jump'}]}
}

I would like to hear your criticism on design principles (srp, dry, kiss etc..), readability (naming of variables, methods) and maintainability (code structure, methods) of the code you see.

Already notes in the comments of the code but:

  • XML provided as input must not contain any XML comments.
  • Mixed data such as: <MyElement>Some <b>Mixed</b> Data</MyElement> is not supported.

Without further ado, lets jump into the code..

Entity classes

XMLElement.java

package xml2json2;

import java.util.ArrayList;
import java.util.List;

public class XMLElement {

    private String elementName; // can not be null
    private String elementValue = "";

    private List<ElementAttribute> attributes = new ArrayList<>(); // can be empty
    private List<XMLElement> children = new ArrayList<>(); // can be empty

    public String getElementName() {
        return elementName;
    }

    public void setElementName(String elementName) {
        this.elementName = elementName;
    }

    public String getElementValue() {
        return elementValue;
    }

    public void setElementValue(String elementValue) {
        this.elementValue = elementValue;
    }

    public List<ElementAttribute> getAttributes() {
        return attributes;
    }


    public List<XMLElement> getChildren() {
        return children;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("XMLElement{");
        sb.append("elementName='").append(elementName).append(''');
        if (!elementValue.equals("")) {
            sb.append(", elementValue='").append(elementValue).append(''');
        }
        if (attributes.size() != 0) {
            sb.append(", attributes=").append(attributes);
        }
        if (children.size() != 0) {
            sb.append(", children=").append(children);
        }
        sb.append('}');
        return sb.toString();
    }
}

ElementAttribute.java

package xml2json2;

public class ElementAttribute {

    private String name;
    private String value;

    public String getName() {
        return name;
    }

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

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("ElementAttribute{");
        sb.append("name='").append(name).append(''');
        sb.append(", value='").append(value).append(''');
        sb.append('}');
        return sb.toString();
    }
}

Processor

XMLElementTreeBuilderImpl.java

package xml2json2;

// References:
// XML Spec  : https://www.liquid-technologies.com/XML
// Regex     : https://regexone.com

/*
    This tree builder does not support elements with mixed data such as: <MyElement>Some <b>Mixed</b> Data</MyElement>.
    Mixed data can contain text and child elements within the containing element. This is typically only used to mark up data (HTML etc).
    Its typically only used to hold mark-up/formatted text entered by a person,
    it is typically not he best choice for storing machine readable data as adds significant complexity to the parser.
 */

/*
    XML to be processed must not contain any comments!
 */

public class XMLElementTreeBuilderImpl {

    private char[] xmlArray;
    private int currentIndex = 0;


    // This class has only 2 public methods:
    public XMLElement buildTreeFromXML(String xml) {
        return buildTreeFromXML(xml.toCharArray());
    }

    public XMLElement buildTreeFromXML(char[] arr) {
        this.xmlArray = arr;
        XMLElement root = nodeFromStringRecursively();
        return root;
    }

    // Everything else below here is private, i.e. inner workings of the class..
    private XMLElement nodeFromStringRecursively() {
        final XMLElement xmlElement = new XMLElement();

        clearWhiteSpace();

        if (tagStart()) { // A new XML Element is starting..
            currentIndex++;
            final String elementName = parseStartingTagElement(); // finishes element name..
            xmlElement.setElementName(elementName);
        }

        clearWhiteSpace();

        // We have not closed our tag yet..
        // At this point we might have attributes.. Lets add them if they exist..
        while (isLetter()) {
            addAttribute(xmlElement);
            clearWhiteSpace();
        }

        // At this point we will have one of the following in current index:
        // [/] -> Self closing tag..
        // [>] -> Tag ending - (Data or children or starting or immediately followed by an ending tag..)

        if (selfClosingTagEnd()) {
            return xmlElement;
        }

        // At this point we are sure this element was not a self closing element..
        currentIndex++; // skipping the tag close character, i.e. '>'

        // At this point we are facing one of the following cases:
        // Assume our starting tag was <foo> for the examples..
        // 1 - [</]                            : Immediate tag end. "</foo>"
        // 2 - [sw]+[</]                      : Any whitespace or any alphanumeric character, one or more repetitions, followed by tag end. "sample</foo>"
        // 3 - [s]*(<![CDATA[...]]>)[s]*[</] : Zero or more white space, followed by CDATA. followed by zero or more white space. "<![CDATA[...]]></foo>
        // 4 - [s]*[<]+                       : Zero or more white space, followed by one or more child start..

        int currentCase = currentCase();

        switch (currentCase) {
            case 1: // Immediate closing tag, no data to set, no children to add.. Do nothing.
                break;
            case 2:
                setData(xmlElement);
                break;
            case 3:
                setCData(xmlElement);
            case 4:
                while (currentCase() == 4) { // Add children recursively.
                    final XMLElement childToken = nodeFromStringRecursively();
                    xmlElement.getChildren().add(childToken);
                }
        }
        walkClosingTag();
        return xmlElement;
    }

    private String parseStartingTagElement() {
        final StringBuilder elementNameBuilder = new StringBuilder();
        while (!isWhiteSpace() && !selfClosingTagEnd() && !tagEnd()) {
            elementNameBuilder.append(charAtCurrentIndex());
            currentIndex++;
        }
        final String elementName = elementNameBuilder.toString();
        return elementName;
    }

    private void addAttribute(XMLElement xmlElement) {
        // Attribute name..
        final StringBuilder attributeNameBuilder = new StringBuilder();
        while (!isWhiteSpace() && charAtCurrentIndex() != '=') {
            attributeNameBuilder.append(charAtCurrentIndex());
            currentIndex++;
        }

        // Everything in between that is not much of interest to us..
        clearWhiteSpace();
        currentIndex++; // Passing the '='
        clearWhiteSpace();
        currentIndex++; // Passing the '"'

        // Attribute value..
        final StringBuilder attributeValueBuilder = new StringBuilder();
        while (charAtCurrentIndex() != '"') {
            attributeValueBuilder.append(charAtCurrentIndex());
            currentIndex++;
        }
        currentIndex++; // Passing the final '"'
        clearWhiteSpace();

        // Build the attribute object and..
        final ElementAttribute elementAttribute = new ElementAttribute();
        elementAttribute.setName(attributeNameBuilder.toString());
        elementAttribute.setValue(attributeValueBuilder.toString());

        // ..add the attribute to the xmlElement
        xmlElement.getAttributes().add(elementAttribute);
    }

    private int currentCase() {
        if (endTagStart()) {
            return 1;
        }
        if (cDataStart()) {
            return 3;
        }
        if (tagStart() && !endTagStart()) {
            return 4;
        }
        // Here we will look forward, so we need to keep track of where we actually started..
        int currentIndexRollBackPoint = currentIndex;
        while (!endTagStart() && !cDataStart() && !tagStart()) {
            currentIndex++;
            if (endTagStart()) {
                currentIndex = currentIndexRollBackPoint;
                return 2;
            }
            if (cDataStart()) {
                currentIndex = currentIndexRollBackPoint;
                return 3;
            }
            if (tagStart() && !endTagStart()) {
                currentIndex = currentIndexRollBackPoint;
                return 4;
            }
        }

        throw new UnsupportedOperationException("Encountered an unsupported XML.");
    }

    private void setData(XMLElement xmlElement) {
        final StringBuilder dataBuilder = new StringBuilder();
        while (!tagStart()) {
            dataBuilder.append(charAtCurrentIndex());
            currentIndex++;
        }
        String data = dataBuilder.toString();

        data = data.replaceAll("&lt;", "<");
        data = data.replaceAll("&gt;", ">");
        data = data.replaceAll("&quot;", """);
        data = data.replaceAll("&apos;", "'");
        data = data.replaceAll("&amp;", "&");


        xmlElement.setElementValue(data);
    }

    private void setCData(XMLElement xmlElement) {
        final StringBuilder cdataBuilder = new StringBuilder();
        while (!endTagStart()) {
            cdataBuilder.append(charAtCurrentIndex());
            currentIndex++;
        }
        String cdata = cdataBuilder.toString();
        cdata = cdata.trim();
        // cutting 9 chars because: <![CDATA[
        cdata = cdata.substring(9, cdata.indexOf(']'));
        xmlElement.setElementValue(cdata);

    }

    private void walkClosingTag() {
        while (!tagEnd()) {
            currentIndex++;
        }
        currentIndex++;
    }

    // Convenience methods
    private void clearWhiteSpace() {
        while (isWhiteSpace()) {
            currentIndex++;
        }
    }

    private boolean isLetter() {
        return Character.isLetter(charAtCurrentIndex());
    }

    private boolean isWhiteSpace() {
        return Character.isWhitespace(charAtCurrentIndex());
    }

    private boolean tagStart() {
        return charAtCurrentIndex() == '<';
    }

    private boolean tagEnd() {
        return charAtCurrentIndex() == '>';
    }

    private boolean endTagStart() {
        return charAtCurrentIndex() == '<' && charAtNextIndex() == '/';
    }

    private boolean selfClosingTagEnd() {
        return charAtCurrentIndex() == '/' && charAtNextIndex() == '>';
    }

    private boolean cDataStart() {
        return charAtCurrentIndex() == '<' && charAtNextIndex() == '!' && xmlArray[currentIndex + 2] == '[';
    }

    private char charAtCurrentIndex() {
        return xmlArray[currentIndex];
    }

    private char charAtNextIndex() {
        return xmlArray[currentIndex + 1];
    }
}

Unit Tests

package xml2json2;

import java.util.List;

public class TreeFromXMLBuilderImplTest {

    private static XMLElementTreeBuilderImpl treeFromXMLBuilder;

    public static void main(String[] args) {
        selfClosingTagWithoutSpace();
        selfClosingTagWithSpace();
        selfClosingTagWithNewLine();
        emptyElementNoSpace();
        emptyElementWithSpace();
        emptyElementWithNewLine();
        selfClosingTagWithAttributeNoSpace();
        selfClosingTagWithAttributeWithSpace();
        selfClosingTagWithMultipleAttributes();
        xmlElementWithData();
        xmlElementWithAttributeAndWithData();
        xmlElementWithChild();
        sampleXMLNote();
        sampleXmlWithGrandChildren();
        withCharacterData();
        dataWithPreDefinedEntities();
    }

    private static void selfClosingTagWithoutSpace() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo/>");
        assert xmlElement.getElementName().equals("foo") : "was : " + xmlElement.getElementName();
    }

    private static void selfClosingTagWithSpace() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo        />");
        assert xmlElement.getElementName().equals("foo") : "was : " + xmlElement.getElementName();
    }

    private static void selfClosingTagWithNewLine() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foonn/>");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
    }

    private static void emptyElementNoSpace() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo></foo>");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
    }

    private static void emptyElementWithSpace() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo></foo        >");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
    }

    private static void emptyElementWithNewLine() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo></foo nnn>");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
    }

    private static void selfClosingTagWithAttributeNoSpace() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo bar="baz"/>");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
        final ElementAttribute attribute = xmlElement.getAttributes().iterator().next();
        assert attribute.getName().equals("bar") : "was: " + attribute.getName();
        assert attribute.getValue().equals("baz") : "was: " + attribute.getValue();
    }

    private static void selfClosingTagWithAttributeWithSpace() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo       bar    =    "baz"      />");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
        final ElementAttribute attribute = xmlElement.getAttributes().iterator().next();
        assert attribute.getName().equals("bar") : "was: " + attribute.getName();
        assert attribute.getValue().equals("baz") : "was: " + attribute.getValue();
    }

    private static void selfClosingTagWithMultipleAttributes() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo bar="baz" qux="booze"/>");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
        ElementAttribute attribute = xmlElement.getAttributes().get(0);
        assert attribute.getName().equals("bar") : "was: " + attribute.getName();
        assert attribute.getValue().equals("baz") : "was: " + attribute.getValue();
        attribute = xmlElement.getAttributes().get(1);
        assert attribute.getName().equals("qux") : "was: " + attribute.getName();
        assert attribute.getValue().equals("booze") : "was: " + attribute.getValue();
    }

    private static void xmlElementWithData() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo>bar</foo>");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
        assert xmlElement.getElementValue().equals("bar") : "was: " + xmlElement.getElementValue();
    }

    private static void xmlElementWithAttributeAndWithData() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo baz = "baz" > bar </foo>");
        assert xmlElement.getElementName().equals("foo") : "was: " + xmlElement.getElementName();
        assert xmlElement.getElementValue().equals(" bar ") : "was: " + xmlElement.getElementValue();
        ElementAttribute attribute = xmlElement.getAttributes().get(0);
        assert attribute.getName().equals("baz") : "was: " + attribute.getName();
        assert attribute.getValue().equals("baz") : "was: " + attribute.getValue();
    }

    private static void xmlElementWithChild() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML("<foo><bar></bar><tar>rat</tar><baz/></foo>");
        assert xmlElement.getElementName().equals("foo");
        assert xmlElement.getAttributes().isEmpty();
        assert xmlElement.getChildren().size() == 3;
        assert xmlElement.getChildren().get(0).getElementName().equals("bar");
        assert xmlElement.getChildren().get(0).getElementValue().equals("");
        assert xmlElement.getChildren().get(1).getElementName().equals("tar");
        assert xmlElement.getChildren().get(1).getElementValue().equals("rat");
        assert xmlElement.getChildren().get(2).getElementName().equals("baz");
        assert xmlElement.getChildren().get(2).getElementValue().equals("");
    }

    private static void sampleXMLNote() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        String note =
                        "<note>n" +
                         "<to>Tove</to>n" +
                         "<from>Jani</from>n" +
                         "<heading>Reminder</heading>n" +
                         "<body>Don't forget me this weekend!</body>n" +
                         "</note>"
                ;
        final XMLElement xmlElement = treeFromXMLBuilder.buildTreeFromXML(note);
        // For visual inspection..
        System.out.println(xmlElement);
    }

    /*
        <foo>
            <bar>
                <baz>test</baz>
            </bar>
            <qux att="tta">
                <fox>jumped</fox>
            </qux>
        </foo>
     */
    private static void sampleXmlWithGrandChildren() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        String sampleWithGrandChildren = "<foo><bar><baz>test</baz></bar><qux att="tta"><fox>jumped</fox></qux></foo>";
        final XMLElement foo = treeFromXMLBuilder.buildTreeFromXML(sampleWithGrandChildren);
        assert foo.getElementName().equals("foo");
        final List<XMLElement> children = foo.getChildren();
        assert children.size() == 2; // bar and qux
        final XMLElement bar = children.get(0);
        assert bar.getElementName().equals("bar");
        assert bar.getElementValue().equals("");
        final List<XMLElement> barChildren = bar.getChildren();
        assert barChildren.size() == 1;
        final XMLElement baz = barChildren.get(0);
        assert baz.getElementName().equals("baz");
        assert baz.getElementValue().equals("test");
        final XMLElement qux = children.get(1);
        assert qux.getAttributes().size() == 1;
        assert qux.getAttributes().get(0).getName().equals("att");
        assert qux.getAttributes().get(0).getValue().equals("tta");
        final List<XMLElement> quxChildren = qux.getChildren();
        assert quxChildren.size() == 1;
        final XMLElement fox = quxChildren.get(0);
        assert fox.getElementName().equals("fox");
        assert fox.getElementValue().equals("jumped");
        // System.out.println(sampleWithGrandChildren);
    }

    private static void withCharacterData() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final String sampleXMLWithCData = "<foo><![CDATA[ This must be preserved!!! ]]></foo>";
        final XMLElement root = treeFromXMLBuilder.buildTreeFromXML(sampleXMLWithCData);
        assert root.getElementName().equals("foo");
        assert root.getElementValue().equals(" This must be preserved!!! ") : "was: " + root.getElementValue();
    }

    private static void dataWithPreDefinedEntities() {
        treeFromXMLBuilder = new XMLElementTreeBuilderImpl();
        final String withCharacterData = "<foo>&lt;&gt;&quot;&apos;&amp;</foo>";
        final XMLElement root = treeFromXMLBuilder.buildTreeFromXML(withCharacterData);
        assert root.getElementValue().equals("<>"'&");
    }
}


Get this bounty!!!

#StackBounty: #java #mongodb #logging #indexing MongoDB 3.6 ClientCursor :: staticYield can't unlock b/c of recursive lock ns:

Bounty: 50

Our prod mongo server is running out of memory with excessive logging of below statement

2018-03-19T20:03:05.627-0500 [conn2] warning: ClientCursor::staticYield can't unlock b/c of recursive lock ns:

    top:{  
       opid:16,
       active:true,
       secs_running:0,
       microsecs_running:254,
       op:"query",
       ns:"users.person",
       query:{  
          findandmodify:"person",
          query:{  
             clientSN:"405F014DE02B33F1",
             status:"New"
          },
          update:{  
             $set:{  
                status:"InProcess"
             },
             $currentDate:{  
                lastUpdateTime:true
             }
          },
          new:true
       },
       client:"10.102.26.26:61299",
       desc:"conn2",
       connectionId:2,
       locks:{  
          ^:"w",
          ^users:"W"
       },
       waitingForLock:false,
       numYields:0,
       lockStats:{  
          timeLockedMicros:{  

          },
          timeAcquiringMicros:{  
             r:0,
             w:1070513
          }
       }
    }

I have checked the MongoDB: How to disable logging the warning: ClientCursor::staticYield can't unlock b/c of recursive lock? which suggests cause of the issue is missing indexes.

I tried runnign the query with explain() as per the above article and Below is the output of db.getCollection('personSync').find({"clientSN":"405F014DE02B33F1","status":"New"}).explain() the query which has the fields of above findandmodify operation

{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 0,
    "nscannedObjects" : 71331,
    "nscanned" : 71331,
    "nscannedObjectsAllPlans" : 71331,
    "nscannedAllPlans" : 71331,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 557,
    "nChunkSkips" : 0,
    "millis" : 59,
    "server" : "SQL01:27017",
    "filterSet" : false,
    "stats" : {
        "type" : "COLLSCAN",
        "works" : 71333,
        "yields" : 557,
        "unyields" : 557,
        "invalidates" : 0,
        "advanced" : 0,
        "needTime" : 71332,
        "needFetch" : 0,
        "isEOF" : 1,
        "docsTested" : 71331,
        "children" : []
    }
} 

so I was referring to article on https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/ to create index, would adding index in below way fix my issue for findandmodify operation in my case? Or do I need to add any more indexes too?

db.users.createIndex({ clientSN:"405F014DE02B33F1", status:"New"})


Get this bounty!!!

#StackBounty: #java #android #android-layout #android-fragments custom seekbar with multi color

Bounty: 100

I am trying to create custom seek bar in android with multicolor. I tried below code

customseekbar.java

int proBarWidth = getWidth();
int proBarHeight = getHeight();
int thumboffset = getThumbOffset();
int lastproX = 0;
int proItemWidth, proItemRight;
for (int i = 0; i < mproItemsList.size(); i++) {
proItem proItem = mproItemsList.get(i);
Paint proPaint = new Paint();
proPaint.setColor(getResources().getColor(proItem.color));

proItemWidth = (int) (proItem.proItemPercentage
        * proBarWidth / 100);

proItemRight = lastproX + proItemWidth;

// for last item give right of the pro item to width of the
// pro bar
if (i == mproItemsList.size() - 1
        && proItemRight != proBarWidth) {
    proItemRight = proBarWidth;
}
Rect proRect = new Rect();
proRect.set(lastproX, thumboffset / 2, proItemRight,
        proBarHeight - thumboffset / 2);
canvas.drawRect(proRect, proPaint);
lastproX = proItemRight;
}
super.onDraw(canvas);

view

<mypackage.customseekbar
android:id="@+id/customseekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
android:progressDrawable="@android:color/transparent"
android:thumb="@drawable/seek_thumb_normal"
android:thumbOffset="12dp" />

I used this method in MainMenuActivity. It gives me result something like below. I referred this link https://azzits.wordpress.com/2013/11/17/customseekbar/
enter image description here

But I am expecting something like below enter image description here

Is there any way to draw this vertical gapped lines? How can I draw this vertical lines?


Get this bounty!!!

#StackBounty: #java #android #touch #teamviewer Android – how teamviewer native touch works

Bounty: 50

I have already read about the android.permission.INJECT_EVENTS and the usage of Instrumentation class, but with it, your app needs system sign, and special installation form into system folder.
I also have read about the adb possibilities to simulate touch, swipe etc.. events, but it is a very limited function which is basically not enought for me.

My question is, that what is the technical background of (for example) teamviewer, which is usable after a normal installation from android market with only a little permission requirement. I have no idea how TeamViewer’s Samsung Quicksupport can simulate touch event’s.

Because I can easily imagine that computer send command to the phone, and the phone make the touch event on a coordinate.

Anybody have any idea about it how teamviewer works on android and how could I write some similar functionality to force touch events considering the fact that their application can be installed via market with little permission?


Get this bounty!!!

#StackBounty: #java #static #classloader #legacy Isolating a static singleton class using class loaders

Bounty: 100

Disclaimer: This is probably not the best solution given the issue, but I’m curious how this implementation could be achieved.

Problem I’m trying to deal with some legacy code which has a singleton defined like bellow:

public class LegacySingleton {
    private static boolean value;

    public static void setup(boolean v) {
        if (value != null) {
            throw new RuntimeException("Already Set up");
        }
        value = v;
        System.out.println("Setup complete");
    }

    public static void teardown() {
        value = null;
        System.out.println("Teardown complete");
    }

    public static boolean getValue() {
        return value;
    }
}

I do not have the ability to change this design and the class is used heavily throughout the code base. The values returned by this singleton can greatly change the functionality of the code. Eg:

public class LegacyRequestHandler {
    public void handleRequest() {
        if (LegacySingleton.getValue()) {
            System.out.println("Path A");
        } else {
            System.out.println("Path B");
        }
    }
}

Right now if I want the code to take Path A, then I have to initialize LegacySingleton in a particular way. If I then want to take Path B I have to re-initialize the LegacySingleton. There is no way of handling requests in parallel which take different paths; meaning for each different configuration of LegacySingleton required I need to launch a separate JVM instance.


My Question Is it possible to isolate this singleton using separate class loaders? I’ve been playing around with the ClassLoader API, but I cant quite figure it out.

I’m imagining it would look something along the lines of this:

public class LegacyRequestHandlerProvider extends Supplier<LegacyRequestHandler> {
    private final boolean value;
    public LegacyRequestHandlerProvider(boolean value) {
        this.value = value;
    }
    @Override
    public LegacyRequestHandler get() {
        LegacySingleton.setup(value);
        return new LegacyRequestHandler();
    }
}

ClassLoader loader1 = new SomeFunkyClassLoaderMagic();
Supplier<LegacyRequestHandler> supplier1 = loader1
    .loadClass("com.project.LegacyRequestHandlerProvider")
    .getConstructor(Boolean.TYPE)
    .newInstance(true);

ClassLoader loader2 = new SomeFunkyClassLoaderMagic();
Supplier<LegacyRequestHandler> supplier2 = loader2
    .loadClass("com.project.LegacyRequestHandlerProvider")
    .getConstructor(Boolean.TYPE)
    .newInstance(false);

LegacyRequestHandler handler1 = supplier1.get();
LegacyRequestHandler handler2 = supplier2.get();


Get this bounty!!!

#StackBounty: #java #angular #google-chrome #tomcat #jersey Server Sent Events not working in Chrome

Bounty: 50

i am developing a web application with angular 4 and java. I am using server sent events to send some text data to the frontend. In the backend i am using jersey and this is my backend code

eventOutput.write(new OutboundEvent.Builder()
       .id(decodedToken)
       .name("responseBody")
       .data(String.class, respBody.toString()).build());

Frontend i am using angular 4 and the code looks like

var evtSource = new EventSource("url");
 source.addEventListener('eventName', (event) => {
    console.log(event);
});

Everything works fine in Mozilla firefox. When i use chrome with tomcat and windows everything works fine. But with tomcat+linux and chrome, i see the error in the console.as

EventSource’s response has a charset (“iso-8859-1”) that is not UTF-8.
Aborting the connection.

What could be the issue. What is the fix? Please help. Any help would be appreciated. Thanks.


Get this bounty!!!