text:
package org.drools.core.runtime.help.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.mapper.Mapper;
import org.drools.core.command.impl.ExecutableCommand;
import org.drools.core.command.runtime.AdvanceSessionTimeCommand;
import org.drools.core.command.runtime.BatchExecutionCommandImpl;
import org.drools.core.command.runtime.GetGlobalCommand;
import org.drools.core.command.runtime.GetSessionTimeCommand;
import org.drools.core.command.runtime.SetGlobalCommand;
import org.drools.core.command.runtime.process.AbortWorkItemCommand;
import org.drools.core.command.runtime.process.CompleteWorkItemCommand;
import org.drools.core.command.runtime.process.SignalEventCommand;
import org.drools.core.command.runtime.process.StartProcessCommand;
import org.drools.core.command.runtime.rule.DeleteCommand;
import org.drools.core.command.runtime.rule.FireAllRulesCommand;
import org.drools.core.command.runtime.rule.FireUntilHaltCommand;
import org.drools.core.command.runtime.rule.GetObjectCommand;
import org.drools.core.command.runtime.rule.GetObjectsCommand;
import org.drools.core.command.runtime.rule.InsertElementsCommand;
import org.drools.core.command.runtime.rule.InsertObjectCommand;
import org.drools.core.command.runtime.rule.ModifyCommand;
import org.drools.core.command.runtime.rule.QueryCommand;
import org.drools.core.common.DefaultFactHandle;
import org.drools.core.runtime.impl.ExecutionResultImpl;
import org.drools.core.runtime.rule.impl.FlatQueryResults;
import org.drools.core.util.StringUtils;
import org.kie.api.command.Command;
import org.kie.api.command.Setter;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;
import org.kie.internal.command.CommandFactory;

public class XStreamJSon {
    public static volatile boolean SORT_MAPS = false;

    public static XStream newJSonMarshaller() {
        JettisonMappedXmlDriver jet = new JettisonMappedXmlDriver();
        XStream xstream = new XStream( jet );

        XStreamHelper.setAliases( xstream );

        xstream.alias( "commands",
                       CommandsObjectContainer.class );
        xstream.alias( "objects",
                       ObjectsObjectContainer.class );
        xstream.alias( "item",
                       RowItemContainer.class );
        xstream.alias( "parameters",
                       ParameterContainer.class );
        xstream.alias( "results",
                       WorkItemResultsContainer.class );

        xstream.setMode( XStream.NO_REFERENCES );

        xstream.registerConverter( new JSonFactHandleConverter( xstream ) );
        xstream.registerConverter( new JSonBatchExecutionResultConverter( xstream ) );
        xstream.registerConverter( new JSonInsertConverter( xstream ) );
        xstream.registerConverter( new JSonFireAllRulesConverter( xstream ) );
        xstream.registerConverter( new JSonBatchExecutionCommandConverter( xstream ) );
        xstream.registerConverter( new CommandsContainerConverter( xstream ) );
        xstream.registerConverter( new JSonGetObjectConverter( xstream ) );
        xstream.registerConverter( new JSonRetractConverter( xstream ) );
        xstream.registerConverter( new JSonModifyConverter( xstream ) );
        xstream.registerConverter( new JSonSetGlobalConverter( xstream ) );
        xstream.registerConverter( new JSonInsertElementsConverter( xstream ) );
        xstream.registerConverter( new JSonGetGlobalConverter( xstream ) );
        xstream.registerConverter( new JSonGetObjectsConverter( xstream ) );
        xstream.registerConverter( new JSonQueryConverter( xstream ) );
        xstream.registerConverter( new JSonQueryResultsConverter( xstream ) );
        xstream.registerConverter( new RowItemConverter( xstream ) );
        xstream.registerConverter( new JSonStartProcessConvert( xstream ) );
        xstream.registerConverter( new JSonSignalEventConverter( xstream ) );
        xstream.registerConverter( new JSonCompleteWorkItemConverter( xstream ) );
        xstream.registerConverter( new JSonAbortWorkItemConverter( xstream ) );
        xstream.registerConverter( new JSonGetSessionTimeConverter( xstream ) );
        xstream.registerConverter( new JSonAdvanceSessionTimeConverter( xstream ) );

        return xstream;
    }

    public static class CommandsContainerConverter extends AbstractCollectionConverter {
        public CommandsContainerConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public boolean canConvert(Class type) {
            return CommandsObjectContainer.class.isAssignableFrom( type );

        }

        @Override
        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            CommandsObjectContainer container = (CommandsObjectContainer) object;

            writeItem( container.getContainedObject(),
                       context,
                       writer );
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            throw new UnsupportedOperationException();
        }

    }

    public static class RowItemConverter extends AbstractCollectionConverter {
        public RowItemConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public boolean canConvert(Class type) {
            return RowItemContainer.class.isAssignableFrom( type );

        }

        @Override
        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            RowItemContainer container = (RowItemContainer) object;

            writer.startNode( "identifier" );
            writer.setValue( container.getIdentifier() );
            writer.endNode();

            writer.startNode( "external-form" );
            writer.setValue( container.getFactHandle().toExternalForm() );
            writer.endNode();

            writer.startNode( "object" );
            writeItem( container.getObject(),
                       context,
                       writer );
            writer.endNode();
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String identifier = null;
            String externalForm = null;
            Object object = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "identifier".equals( nodeName ) ) {
                    identifier = reader.getValue();
                } else if ( "external-form".equals( nodeName ) ) {
                    externalForm = reader.getValue();
                } else if ( "object".equals( nodeName ) ) {
                    reader.moveDown();
                    object = readItem( reader,
                                       context,
                                       null );
                    reader.moveUp();
                }
                reader.moveUp();
            }
            return new RowItemContainer( identifier,
                                         DefaultFactHandle.createFromExternalFormat( externalForm ),
                                         object );
        }

    }

    public static class JSonBatchExecutionCommandConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonBatchExecutionCommandConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            BatchExecutionCommandImpl cmds = (BatchExecutionCommandImpl) object;
            if ( cmds.getLookup() != null ) {
                writer.startNode( "lookup" );
                writer.setValue( cmds.getLookup() );
                writer.endNode();
            }

            for ( Command cmd : cmds.getCommands() ) {
                writeItem( new CommandsObjectContainer( cmd ),
                           context,
                           writer );
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            List<Command> list = new ArrayList<Command>();
            String lookup = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                if ( "commands".equals( reader.getNodeName() ) ) {
                    while ( reader.hasMoreChildren() ) {
                        reader.moveDown();
                        ExecutableCommand cmd = (ExecutableCommand) readItem( reader,
                                                                              context,
                                                                              null );
                        list.add( cmd );
                        reader.moveUp();
                    }
                } else if ( "lookup".equals( reader.getNodeName() ) ) {
                    lookup = reader.getValue();
                } else {
                    throw new IllegalArgumentException( "batch-execution does not support the child element name=''" + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
                }
                reader.moveUp();
            }
            return new BatchExecutionCommandImpl( list, lookup );
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( BatchExecutionCommandImpl.class );
        }
    }

    public static class JSonInsertConverter extends BaseConverter
        implements
        Converter {

        public JSonInsertConverter(XStream xstream) {
            super( xstream );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            InsertObjectCommand cmd = (InsertObjectCommand) object;
            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();

                writer.startNode( "return-object" );
                writer.setValue( Boolean.toString( cmd.isReturnObject() ) );
                writer.endNode();
            }

            if ( !StringUtils.isEmpty( cmd.getEntryPoint() ) ) {
                writer.startNode( "entry-point" );
                writer.setValue(  cmd.getEntryPoint() );
                writer.endNode();
            }
            writeValue( writer,
                        context,
                        "object",
                        cmd.getObject() );
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            InsertObjectCommand cmd = new InsertObjectCommand();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "out-identifier".equals( nodeName ) ) {
                    cmd.setOutIdentifier( reader.getValue() );
                } else if ( "return-object".equals( nodeName ) ) {
                    cmd.setReturnObject( Boolean.parseBoolean( reader.getValue() ) );
                } else if ( "object".equals( nodeName ) ) {
                    cmd.setObject( readValue( reader,
                                              context,
                                              cmd.getObject(),
                                              "object" ) );
                } else if ( "entry-point".equals( nodeName ) ) {
                    cmd.setEntryPoint( reader.getValue() );
                }
                reader.moveUp();

            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( InsertObjectCommand.class );
        }

    }

    public static class JSonFactHandleConverter extends AbstractCollectionConverter
        implements
        Converter {
        public JSonFactHandleConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public boolean canConvert(Class aClass) {
            return FactHandle.class.isAssignableFrom( aClass );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext marshallingContext) {
            FactHandle fh = (FactHandle) object;
            writer.startNode( "external-form" );
            writer.setValue( fh.toExternalForm() );
            writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext unmarshallingContext) {
            reader.moveDown();
            DefaultFactHandle factHandle = DefaultFactHandle.createFromExternalFormat( reader.getValue() );
            reader.moveUp();
            return factHandle;
        }
    }

    public static class JSonFireAllRulesConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonFireAllRulesConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            FireAllRulesCommand cmd = (FireAllRulesCommand) object;

            if ( cmd.getMax() != -1 ) {
                writer.startNode( "max" );
                writer.setValue( Integer.toString( cmd.getMax() ) );
                writer.endNode();
            }

            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String max = null;
            String outIdentifier = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                if ( "max".equals( reader.getNodeName() ) ) {
                    max = reader.getValue();
                } else if ( "out-identifier".equals( reader.getNodeName() ) ) {
                    outIdentifier = reader.getValue();
                } else {
                    throw new IllegalArgumentException( "fire-all-rules does not support the child element name=''" + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
                }
                reader.moveUp();
            }

            FireAllRulesCommand cmd;

            if ( max != null ) {
                cmd = new FireAllRulesCommand( Integer.parseInt( max ) );
            } else {
                cmd = new FireAllRulesCommand();
            }
            if ( outIdentifier != null ) {
                cmd.setOutIdentifier(outIdentifier);
            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( FireAllRulesCommand.class );
        }
    }

    public static class JSonFireUntilHaltConverter extends AbstractCollectionConverter
            implements Converter {

        public JSonFireUntilHaltConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                HierarchicalStreamWriter writer,
                MarshallingContext context) {
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                UnmarshallingContext context) {
            if ( reader.hasMoreChildren() ) {
                throw new IllegalArgumentException( "fire-until-halt does not support the child element name=''"
                        + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
            }
            return new FireAllRulesCommand();
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( FireUntilHaltCommand.class );
        }
    }

    public static class JSonGetObjectConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonGetObjectConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            GetObjectCommand cmd = (GetObjectCommand) object;
            writer.startNode( "fact-handle" );
            writer.setValue( cmd.getFactHandle().toExternalForm() );
            writer.endNode();

            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            FactHandle factHandle = null;
            String outIdentifier = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String name = reader.getNodeName();
                if ( "fact-handle".equals( name ) ) {
                    factHandle = DefaultFactHandle.createFromExternalFormat( reader.getValue() );
                } else if ( "out-identifier".equals( name ) ) {
                    outIdentifier = reader.getValue();
                }
                reader.moveUp();
            }

            GetObjectCommand cmd = new GetObjectCommand( factHandle );
            if ( outIdentifier != null ) {
                cmd.setOutIdentifier( outIdentifier );
            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( GetObjectCommand.class );
        }
    }

    public static class JSonRetractConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonRetractConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            DeleteCommand cmd = (DeleteCommand) object;
            writer.startNode( "fact-handle" );
            writer.setValue( cmd.getFactHandle().toExternalForm() );
            writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            reader.moveDown();
            FactHandle factHandle = DefaultFactHandle.createFromExternalFormat( reader.getValue() );
            reader.moveUp();

            return CommandFactory.newDelete(factHandle);
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( DeleteCommand.class );
        }
    }

    public static class JSonModifyConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonModifyConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            ModifyCommand cmd = (ModifyCommand) object;

            writer.startNode( "fact-handle" );
            writer.setValue( cmd.getFactHandle().toExternalForm() );
            writer.endNode();

            List<Setter> setters = cmd.getSetters();
            for ( Setter setter : setters ) {
                writeItem( setter,
                           context,
                           writer );

            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            reader.moveDown();
            FactHandle factHandle = DefaultFactHandle.createFromExternalFormat( reader.getValue() );
            reader.moveUp();

            List<Setter> setters = new ArrayList<Setter>();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();

                reader.moveDown();
                String accessor = reader.getValue();
                reader.moveUp();

                reader.moveDown();
                String value = reader.getValue();
                reader.moveUp();

                Setter setter = CommandFactory.newSetter( accessor,
                                                          value );
                setters.add( setter );

                reader.moveUp();
            }

            return CommandFactory.newModify( factHandle,
                                             setters );
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( ModifyCommand.class );
        }

    }

    public static class JSonInsertElementsConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonInsertElementsConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            InsertElementsCommand cmd = (InsertElementsCommand) object;

            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();

                writer.startNode( "return-objects" );
                writer.setValue( Boolean.toString( cmd.isReturnObject() ) );
                writer.endNode();

            }
            if ( !StringUtils.isEmpty( cmd.getEntryPoint() ) ) {
                writer.startNode( "entry-point" );
                writer.setValue(  cmd.getEntryPoint() );
                writer.endNode();
            }

            for ( Object element : cmd.getObjects() ) {
                writeItem( new ObjectsObjectContainer( element ),
                           context,
                           writer );
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            List<Object> objects = new ArrayList<Object>();
            String outIdentifier = null;
            String returnObjects = null;
            String entryPoint = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "objects".equals( nodeName ) ) {
                    while ( reader.hasMoreChildren() ) {
                        reader.moveDown();
                        Object o = readItem( reader,
                                             context,
                                             null );
                        objects.add( o );
                        reader.moveUp();
                    }
                } else if ( "out-identifier".equals( nodeName ) ) {
                    outIdentifier = reader.getValue();
                } else if ( "return-objects".equals( nodeName ) ) {
                    returnObjects = reader.getValue();
                } else if ( "entry-point".equals( nodeName ) ) {
                    entryPoint = reader.getValue();
                } else {
                    throw new IllegalArgumentException( "insert-elements does not support the child element name=''" + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
                }
                reader.moveUp();
            }
            InsertElementsCommand cmd = new InsertElementsCommand( objects );
            if ( outIdentifier != null ) {
                cmd.setOutIdentifier( outIdentifier );
                if ( returnObjects != null ) {
                    cmd.setReturnObject( Boolean.parseBoolean( returnObjects ) );
                }
            }
            if ( entryPoint != null ) {
                cmd.setEntryPoint( entryPoint );
            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( InsertElementsCommand.class );
        }
    }

    public static class JSonBatchExecutionResultConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonBatchExecutionResultConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            ExecutionResults result = (ExecutionResults) object;
            writer.startNode( "results" );
            if ( !result.getIdentifiers().isEmpty() ) {

                Collection<String> identifiers = result.getIdentifiers();
                // this gets sorted, otherwise unit tests will not pass
                if ( SORT_MAPS ) {
                    String[] array = identifiers.toArray( new String[identifiers.size()]);
                    Arrays.sort(array);
                    identifiers = Arrays.asList(array);
                }

                for ( String identifier : identifiers ) {
                    writer.startNode( "result" );

                    writer.startNode( "identifier" );
                    writer.setValue( identifier );
                    writer.endNode();

                    writer.startNode( "value" );
                    Object value = result.getValue( identifier );
                    if ( value instanceof org.kie.api.runtime.rule.QueryResults ) {
                        String name = mapper().serializedClass(FlatQueryResults.class);
                        ExtendedHierarchicalStreamWriterHelper.startNode(writer, name, FlatQueryResults.class);
                        context.convertAnother(value);
                        writer.endNode();
                    } else {
                        writeItem( value,
                                   context,
                                   writer );
                    }
                    writer.endNode();

                    writer.endNode();
                }
            }

            Collection<String> handles = ((ExecutionResultImpl) result).getFactHandles().keySet();
            // this gets sorted, otherwise unit tests will not pass
            if (SORT_MAPS) {
                String[] array = handles.toArray( new String[handles.size()]);
                Arrays.sort(array);
                handles = Arrays.asList(array);
            }

            for ( String identifier : handles ) {
                Object handle = result.getFactHandle( identifier );
                if ( handle instanceof FactHandle ) {
                    writer.startNode( "fact-handle" );

                    writer.startNode( "identifier" );
                    writer.setValue( identifier );
                    writer.endNode();

                    writer.startNode( "external-form" );
                    writer.setValue( ((FactHandle) handle).toExternalForm() );
                    writer.endNode();

                    writer.endNode();
                } else if ( handle instanceof Collection ) {
                    writer.startNode( "fact-handles" );

                    writer.startNode( "identifier" );
                    writer.setValue( identifier );
                    writer.endNode();

                    //writer.startNode( "xxx" );
                    for ( FactHandle factHandle : (Collection<FactHandle>) handle ) {
                        writeItem( factHandle.toExternalForm(),
                                   context,
                                   writer );
                    }
                    //writer.endNode();

                    writer.endNode();
                }
            }

            writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            ExecutionResultImpl result = new ExecutionResultImpl();
            Map<String, Object> results = result.getResults();
            Map<String, Object> facts = result.getFactHandles();

            reader.moveDown();
            if ( "results".equals( reader.getNodeName() ) ) {
                while ( reader.hasMoreChildren() ) {
                    reader.moveDown();

                    if ( reader.getNodeName().equals( "result" ) ) {
                        reader.moveDown();
                        String identifier = reader.getValue();
                        reader.moveUp();

                        reader.moveDown();
                        reader.moveDown();
                        Object value = readItem( reader,
                                                 context,
                                                 null );
                        results.put( identifier,
                                     value );
                        reader.moveUp();
                        reader.moveUp();
                    } else if ( reader.getNodeName().equals( "fact-handle" ) ) {
                        reader.moveDown();
                        String identifier = reader.getValue();
                        reader.moveUp();

                        reader.moveDown();
                        String externalForm = reader.getValue();
                        reader.moveUp();

                        facts.put( identifier,
                                   DefaultFactHandle.createFromExternalFormat( externalForm ) );
                    } else if ( reader.getNodeName().equals( "fact-handles" ) ) {
                        List<FactHandle> list = new ArrayList<FactHandle>();
                        String identifier = null;
                        while ( reader.hasMoreChildren() ) {
                            reader.moveDown();
                            identifier = reader.getValue();
                            reader.moveUp();
                            while ( reader.hasMoreChildren() ) {
                                reader.moveDown();
                                FactHandle factHandle = DefaultFactHandle.createFromExternalFormat( (String) readItem( reader,
                                                                                context,
                                                                                null ) );
                                list.add( factHandle );
                                reader.moveUp();
                            }
                        }
                        facts.put( identifier,
                                   list );
                    } else {
                        throw new IllegalArgumentException( "Element '" + reader.getNodeName() + "' is not supported here" );
                    }
                    reader.moveUp();
                }
            } else {
                throw new IllegalArgumentException( "Element '" + reader.getNodeName() + "' is not supported here" );
            }
            reader.moveUp();

            return result;
        }

        public boolean canConvert(Class clazz) {
            return ExecutionResults.class.isAssignableFrom( clazz );
        }
    }

    public static abstract class BaseConverter {
        protected Mapper             mapper;
        protected ReflectionProvider reflectionProvider;

        public BaseConverter(XStream xstream) {
            this.mapper = xstream.getMapper();
            this.reflectionProvider = xstream.getReflectionProvider();
        }

        protected void writeValue(HierarchicalStreamWriter writer,
                                  MarshallingContext context,
                                  String fieldName,
                                  Object object) {
            writer.startNode( fieldName );
            String name = this.mapper.serializedClass( object.getClass() );
            ExtendedHierarchicalStreamWriterHelper.startNode( writer,
                                                              name,
                                                              Mapper.Null.class );
            context.convertAnother( object );
            writer.endNode();
            writer.endNode();
        }

        protected Object readValue(HierarchicalStreamReader reader,
                                   UnmarshallingContext context,
                                   Object object,
                                   Object fieldName) {
            reader.moveDown();
            Class type = readClassType( reader,
                                        this.mapper);
            Object o = context.convertAnother( null,
                                               type );

            reader.moveUp();
            return o;
        }

        // methods borrowed directly from com.thoughtworks.xstream.core.util.HierarchicalStreams to make sure we don't
        // depend on that package (it is XStream internal package and using it causes issues in OSGi)
        // see https://issues.jboss.org/browse/DROOLS-558 for more details
        private Class readClassType( HierarchicalStreamReader reader, Mapper mapper ) {
            String classAttribute = readClassAttribute( reader, mapper );
            Class type;
            if ( classAttribute == null ) {
                type = mapper.realClass( reader.getNodeName() );
            } else {
                type = mapper.realClass( classAttribute );
            }
            return type;
        }

        private String readClassAttribute( HierarchicalStreamReader reader, Mapper mapper ) {
            String attributeName = mapper.aliasForSystemAttribute( "resolves-to" );
            String classAttribute = attributeName == null ? null : reader.getAttribute( attributeName );
            if (classAttribute == null) {
                attributeName = mapper.aliasForSystemAttribute( "class" );
                if (attributeName != null) {
                    classAttribute = reader.getAttribute( attributeName );
                }
            }
            return classAttribute;
        }
    }

    public static class JSonSetGlobalConverter extends BaseConverter
        implements
        Converter {

        public JSonSetGlobalConverter(XStream xstream) {
            super( xstream );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            SetGlobalCommand cmd = (SetGlobalCommand) object;

            writer.startNode( "identifier" );
            writer.setValue( cmd.getIdentifier() );
            writer.endNode();

            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }
            writeValue( writer,
                        context,
                        "object",
                        cmd.getObject() );

        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String identifier = null;
            boolean out = false;
            String outIdentifier = null;
            SetGlobalCommand cmd = new SetGlobalCommand();

            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "identifier".equals( nodeName ) ) {
                    identifier = reader.getValue();
                } else if ( "out".equals( nodeName ) ) {
                    out = Boolean.valueOf(reader.getValue());
                } else if ( "out-identifier".equals( nodeName ) ) {
                    outIdentifier = reader.getValue();
                } else if ( "object".equals( nodeName ) ) {
                    cmd.setObject( readValue( reader,
                                              context,
                                              cmd.getObject(),
                                              "object" ) );
                }
                reader.moveUp();
            }

            cmd.setIdentifier( identifier );

            if ( outIdentifier != null ) {
                cmd.setOutIdentifier( outIdentifier );
            } else if (out) {
                cmd.setOutIdentifier( identifier );
            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( SetGlobalCommand.class );
        }

    }

    public static class JSonGetGlobalConverter extends BaseConverter
        implements
        Converter {

        public JSonGetGlobalConverter(XStream xstream) {
            super( xstream );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            GetGlobalCommand cmd = (GetGlobalCommand) object;

            writer.startNode( "identifier" );
            writer.setValue( cmd.getIdentifier() );
            writer.endNode();

            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }

        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String identifier = null;
            String outIdentifier = null;
            GetGlobalCommand cmd = new GetGlobalCommand();

            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "identifier".equals( nodeName ) ) {
                    identifier = reader.getValue();
                } else if ( "out-identifier".equals( nodeName ) ) {
                    outIdentifier = reader.getValue();
                }
                reader.moveUp();
            }

            cmd.setIdentifier( identifier );

            if ( outIdentifier != null ) {
                cmd.setOutIdentifier( outIdentifier );
            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( GetGlobalCommand.class );
        }
    }

    public static class JSonGetObjectsConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonGetObjectsConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            GetObjectsCommand cmd = (GetObjectsCommand) object;

            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String outIdentifier = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                if ( "out-identifier".equals( reader.getNodeName() ) ) {
                    outIdentifier = reader.getValue();
                }
                reader.moveUp();
            }

            GetObjectsCommand cmd = new GetObjectsCommand();
            if ( outIdentifier != null ) {
                cmd.setOutIdentifier( outIdentifier );
            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( GetObjectsCommand.class );
        }
    }

    public static class JSonQueryConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonQueryConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            QueryCommand cmd = (QueryCommand) object;

            writer.startNode( "out-identifier" );
            writer.setValue( cmd.getOutIdentifier() );
            writer.endNode();

            writer.startNode( "name" );
            writer.setValue( cmd.getName() );
            writer.endNode();

            if ( cmd.getArguments() != null && cmd.getArguments().size() > 0 ) {
                writer.startNode( "args" );
                for ( Object arg : cmd.getArguments() ) {
                    writeItem( arg,
                               context,
                               writer );
                }
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String outIdentifier = null;
            String name = null;
            List<Object> args = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "out-identifier".equals( nodeName ) ) {
                    outIdentifier = reader.getValue();
                } else if ( "name".equals( nodeName ) ) {
                    name = reader.getValue();
                } else if ( "args".equals( nodeName ) ) {
                    args = new ArrayList<Object>();
                    while ( reader.hasMoreChildren() ) {
                        reader.moveDown();
                        Object arg = readItem( reader,
                                               context,
                                               null );
                        args.add( arg );
                        reader.moveUp();
                    }
                }
                reader.moveUp();
            }

            return new QueryCommand( outIdentifier,
                                     name,
                                     (args != null) ? args.toArray( new Object[args.size()] ) : null );
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( QueryCommand.class );
        }
    }

    public static class JSonQueryResultsConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonQueryResultsConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            QueryResults results = (QueryResults) object;

            // write out identifiers
            String[] identifiers = results.getIdentifiers();

            writer.startNode( "identifiers" );
            for ( String identifier : identifiers ) {
                writeItem( identifier,
                           context,
                           writer );
            }
            writer.endNode();

            for ( QueryResultsRow result : results ) {
                writer.startNode( "row" );
                for ( String identifier : identifiers ) {
                    Object value = result.get( identifier );
                    FactHandle factHandle = result.getFactHandle( identifier );
                    writeItem( new RowItemContainer( identifier,
                                                     factHandle,
                                                     value),
                               context,
                               writer );
                }
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            reader.moveDown();
            Set<String> identifiers = new TreeSet<String>();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                identifiers.add( (String) readItem( reader,
                                             context,
                                             null ) );
                reader.moveUp();
            }
            reader.moveUp();

            ArrayList<Map<String, Object>> idResults = new ArrayList<Map<String,Object>>();
            ArrayList<Map<String, FactHandle>> idHandles = new ArrayList<Map<String, FactHandle>>();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                Map<String, Object> idResultMap = new HashMap<String, Object>();
                Map<String, FactHandle> idFactHandleMap = new HashMap<String, FactHandle>();
                while ( reader.hasMoreChildren() ) {
                    reader.moveDown();
                    RowItemContainer container = (RowItemContainer) readItem( reader,
                                                                              context,
                                                                              null );

                    String id = container.getIdentifier();
                    idResultMap.put(id, container.getObject());
                    idFactHandleMap.put(id, container.getFactHandle());
                    reader.moveUp();
                }
                idResults.add( idResultMap );
                idHandles.add( idFactHandleMap );
                reader.moveUp();
            }

            return new FlatQueryResults( identifiers,
                                         idHandles,
                                         idResults );
        }

        public boolean canConvert(Class clazz) {
            return QueryResults.class.isAssignableFrom( clazz );
        }
    }

    public static class JSonStartProcessConvert extends AbstractCollectionConverter
        implements
        Converter {

        public JSonStartProcessConvert(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            StartProcessCommand cmd = (StartProcessCommand) object;
            writer.startNode( "process-id" );
            writer.setValue( cmd.getProcessId() );
            writer.endNode();

            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }

            for ( Entry<String, Object> entry : cmd.getParameters().entrySet() ) {
                writeItem( new ParameterContainer( entry.getKey(),
                                                   entry.getValue() ),
                           context,
                           writer );
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            reader.moveDown();
            String processId = reader.getValue();
            reader.moveUp();

            String outIdentifier = null;
            HashMap<String, Object> params = new HashMap<String, Object>();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                if ( "parameters".equals( reader.getNodeName() ) ) {
                    ParameterContainer parameterContainer = (ParameterContainer) readItem( reader,
                                                                                context,
                                                                                null );
                    params.put( parameterContainer.getIdentifier(),
                                parameterContainer.getObject() );
                } else if ( "out-identifier".equals( reader.getNodeName() ) ) {
                    outIdentifier = reader.getValue();
                } else {
                    throw new IllegalArgumentException( "start-process does not support the child element name=''" + reader.getNodeName() + "' value=" + reader.getValue() + "'" );
                }
                reader.moveUp();
            }

            StartProcessCommand cmd = new StartProcessCommand();
            cmd.setProcessId( processId );
            cmd.setParameters( params );
            if ( outIdentifier != null ) {
                cmd.setOutIdentifier( outIdentifier );
            }

            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( StartProcessCommand.class );
        }
    }

    public static class JSonSignalEventConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonSignalEventConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            SignalEventCommand cmd = (SignalEventCommand) object;
            long processInstanceId = cmd.getProcessInstanceId();
            String eventType = cmd.getEventType();
            Object event = cmd.getEvent();

            if ( processInstanceId != -1 ) {
                writer.startNode( "process-instance-id" );
                writer.setValue( Long.toString( processInstanceId ) );
                writer.endNode();
            }

            writer.addAttribute( "event-type",
                                 eventType );

            writer.startNode( "event-type" );
            writer.setValue( eventType );
            writer.endNode();

            writer.startNode( "object" );
            writeItem( event,
                       context,
                       writer );
            writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String processInstanceId = null;
            String eventType = null;
            Object event = null;
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "process-instance-id".equals( nodeName ) ) {
                    processInstanceId = reader.getValue();
                } else if ( "event-type".equals( nodeName ) ) {
                    eventType = reader.getValue();
                } else if ( "object".equals( nodeName ) ) {
                    reader.moveDown();
                    event = readItem( reader,
                                      context,
                                      null );
                    reader.moveUp();
                }
                reader.moveUp();
            }

            Command cmd;
            if ( processInstanceId != null ) {
                cmd = CommandFactory.newSignalEvent( Long.parseLong( processInstanceId ),
                                                     eventType,
                                                     event );
            } else {
                cmd = CommandFactory.newSignalEvent( eventType,
                                                     event );
            }

            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( SignalEventCommand.class );
        }

    }

    public static class JSonCompleteWorkItemConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonCompleteWorkItemConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            CompleteWorkItemCommand cmd = (CompleteWorkItemCommand) object;

            writer.startNode( "id" );
            writer.setValue( Long.toString( cmd.getWorkItemId() ) );
            writer.endNode();

            for ( Entry<String, Object> entry : cmd.getResults().entrySet() ) {
                writeItem( new WorkItemResultsContainer( entry.getKey(),
                                                         entry.getValue() ),
                           context,
                           writer );
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            String id = null;
            Map<String, Object> results = new HashMap<String, Object>();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "id".equals( nodeName ) ) {
                    id = reader.getValue();
                } else if ( "results".equals( nodeName ) ) {
                    while ( reader.hasMoreChildren() ) {
                        WorkItemResultsContainer res = (WorkItemResultsContainer) readItem( reader,
                                                                                context,
                                                                                null );
                        results.put( res.getIdentifier(),
                                     res.getObject() );
                    }
                }
                reader.moveUp();
            }

            return new CompleteWorkItemCommand( Long.parseLong( id ),
                                                results );
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( CompleteWorkItemCommand.class );
        }
    }

    public static class JSonAbortWorkItemConverter extends AbstractCollectionConverter
        implements
        Converter {

        public JSonAbortWorkItemConverter(XStream xstream) {
            super( xstream.getMapper() );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            AbortWorkItemCommand cmd = (AbortWorkItemCommand) object;
            writer.startNode( "id" );
            writer.setValue( Long.toString( cmd.getWorkItemId() ) );
            writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            reader.moveDown();
            String id = reader.getValue();
            reader.moveUp();

            return CommandFactory.newAbortWorkItem( Long.parseLong( id ) );
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( AbortWorkItemCommand.class );
        }
    }

    public static class JSonGetSessionTimeConverter extends BaseConverter
            implements
            Converter {

        public JSonGetSessionTimeConverter(XStream xstream) {
            super( xstream );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            GetSessionTimeCommand cmd = (GetSessionTimeCommand) object;
            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            GetSessionTimeCommand cmd = new GetSessionTimeCommand();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "out-identifier".equals( nodeName ) ) {
                    cmd.setOutIdentifier( reader.getValue() );
                }
                reader.moveUp();

            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( GetSessionTimeCommand.class );
        }

    }

    public static class JSonAdvanceSessionTimeConverter extends BaseConverter
            implements
            Converter {

        public JSonAdvanceSessionTimeConverter(XStream xstream) {
            super( xstream );
        }

        public void marshal(Object object,
                            HierarchicalStreamWriter writer,
                            MarshallingContext context) {
            AdvanceSessionTimeCommand cmd = (AdvanceSessionTimeCommand) object;
            if ( cmd.getOutIdentifier() != null ) {
                writer.startNode( "out-identifier" );
                writer.setValue( cmd.getOutIdentifier() );
                writer.endNode();
            }

            writer.startNode( "amount" );
            writer.setValue( "" + cmd.getAmount() );
            writer.endNode();

            writer.startNode( "unit" );
            writer.setValue( "" + cmd.getUnit() );
            writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                                UnmarshallingContext context) {
            AdvanceSessionTimeCommand cmd = new AdvanceSessionTimeCommand();
            while ( reader.hasMoreChildren() ) {
                reader.moveDown();
                String nodeName = reader.getNodeName();
                if ( "out-identifier".equals( nodeName ) ) {
                    cmd.setOutIdentifier( reader.getValue() );
                } else if ( "amount".equals( nodeName ) ) {
                    cmd.setAmount( Long.parseLong( reader.getAttribute( "amount" ) ) );
                } else if ( "unit".equals( nodeName ) ) {
                    cmd.setUnit( TimeUnit.valueOf( reader.getAttribute( "unit" ).toUpperCase() ) );
                }
                reader.moveUp();

            }
            return cmd;
        }

        public boolean canConvert(Class clazz) {
            return clazz.equals( AdvanceSessionTimeCommand.class );
        }

    }
}


text:
package org.araneaframework.http;

import java.io.Serializable;
import java.util.Map;
import org.araneaframework.framework.LocalizationContext;

/**
 * A way to pass custom data back to client-side via AJAX requests.
 *
 * @author Alar Kvell (alar@araneaframework.org)
 * @since 1.1
 */
public interface UpdateRegionProvider extends Serializable {

  /**
   * Will be called only when update-region filter is activated on AJAX requests.
   *
   * @param locCtx Localization context for resolving region labels (e.g. in messages region). If the messages context
   *          is not rendered then probably the context is not needed.
   * @return A map containing regions that will be passed to client-side. Map must have region names as
   *         String keys and region contents as String values. Region contents will be passed
   *         to client-side Javascript region handler, designated by region name. May return null or empty
   *         map. If map contains a null value, then that region is not included in response.
   */
  Map<String, String> getRegions(LocalizationContext locCtx);

}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Aurora - A HTTP Application Server of PHP Script
 *
 * @author  panlatent@gmail.com
 * @link    https://github.com/panlatent/aurora
 * @license https://opensource.org/licenses/MIT
 */

namespace Aurora\Event;

interface EventAcceptable
{
    const EVENT_CALLBACK = 'acceptEvent';

    /**
     * @param string $name
     * @param array  $params
     *
     * @return void
     */
    public function acceptEvent($name, $params = []);
}


text:
import * as models from "../../../models";
import Promise from 'bluebird';
import { extractAllParams } from "../../../utils";
import { HttpError } from "../../../utils/http-error";

/**
 * @param req
 * @param res
 * @param next
 * @return {*}
 */
export function revokeGroupRegisterLinkRequest (req, res, next) {
  return Promise.resolve().then(() => {
    return revokeGroupRegisterLink(
      extractAllParams( req )
    );
  }).then(result => res.json(result)).catch(next);
}

/**
 * @param params
 * @return {Promise<*>}
 */
export async function revokeGroupRegisterLink (params) {
  let {
    linkUuid, link
  } = params;

  if (!link) {
    link = await models.RegisterLink.findByPrimary( linkUuid );
  }

  if (!link) {
    throw new HttpError( 'Такой ссылки не существует' );
  }

  return link.update({
    isActive: false
  });
}


text:
@protocol PrinterConnectivityDelegate <NSObject>

- (void)connectedPrinterDidChangeTo:(Printer *)printer;

@end

@class Printer,GlobalNavigationViewController;
@interface ViewController : UIViewController <Printable, PrinterDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

- (void)addDelegate:(id<PrinterConnectivityDelegate>)delegate;
- (void)removeDelegate:(id<PrinterConnectivityDelegate>)delegate;

+ (NSString *)iconForPrinterStatus:(PrinterStatus)status;
+ (NSString *)statusMessageForPrinterStatus:(PrinterStatus)status;

@end


text:
package com.phostersoft.cookingdiary;

import com.phostersoft.cookingdiary.R;
import com.phostersoft.cookingdiary.dataaccess.DBAdapter;
import com.phostersoft.cookingdiary.utils.IndexedCursorAdaptor;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.TextView;

public class RecipeListView extends ListActivity {
	public static final int INSERT_ID = Menu.FIRST;

	private DBAdapter dbAdapter;
	private Cursor c;
	private TextWatcher textWatcher;
	private ListView listView;
	private IndexedCursorAdaptor recipes;
	private EditText filterText;
	private int tagFilter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (savedInstanceState == null) {
			tagFilter = getIntent().getIntExtra("tagFilter", -1);
		} else {
			restoreState(savedInstanceState);
		}

		setContentView(R.layout.recipe_list);
		dbAdapter = new DBAdapter(this);
		dbAdapter.open();
		fillData();

		listView = getListView();
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				viewRecipe(view);
			}
		});

		textWatcher = new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
				filterText(s.toString());
			}
		};

		filterText = (EditText) findViewById(R.id.filter);
		filterText.addTextChangedListener(textWatcher);

		registerForContextMenu(listView);

	}

	private void restoreState(Bundle savedInstanceState) {
		filterText.setText(
				(String) savedInstanceState.getSerializable("filterText"));
		tagFilter = (Integer)
				savedInstanceState.getSerializable("tagFilter");
		filterText(filterText.getText().toString());
	}

	private void filterText(String string) {
		recipes.getFilter().filter(string);
		recipes.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, INSERT_ID, 0, "New recipe");
		return result;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.recipe_list_context_menu, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case INSERT_ID:
			createNewRecipe();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.edit:
			editRecipe(menuInfo.id);
			return true;
		case R.id.delete:
			deleteRecipe(menuInfo.id);
			return true;
		}
		return super.onContextItemSelected(item);
	}

	private void createNewRecipe() {
    	Intent intent = new Intent(this, RecipeEditorView.class);
    	startActivity(intent);
	}

	private void fillData() {
		c = dbAdapter.fetchRecipeWithTagByTitle(null, tagFilter);
		startManagingCursor(c);

		FilterQueryProvider fqp = new FilterQueryProvider() {

			public Cursor runQuery(CharSequence constraint) {
				c = dbAdapter.fetchRecipeWithTagByTitle(constraint == null ? null :
					constraint.toString(), tagFilter);
				startManagingCursor(c);
				return c;
			}
		};

		String[] from = new String[] {"title"};
		int[] to = new int[] {R.id.recipeText};

		recipes =
				new IndexedCursorAdaptor(this,
						R.layout.recipe_list_item, c, from, to);
		recipes.setFilterQueryProvider(fqp);

		setListAdapter(recipes);
		if (tagFilter == -1 && c.getCount() == 0) {
			TextView empty = (TextView) getListView().getEmptyView();
			empty.setText(R.string.recipelist_norecipe);
		}
	}

	public void viewRecipe(View view) {
    	Intent intent = new Intent(this, RecipeViewer.class);
    	intent.putExtra("recipeId", c.getInt(0));
    	startActivity(intent);
	}

	public void editRecipe(long id) {
    	Intent intent = new Intent(this, RecipeEditorView.class);
    	intent.putExtra("recipeId", c.getInt(0));
    	startActivity(intent);
	}

	public void deleteRecipe(long id) {
		Cursor c2 = dbAdapter.fetchRecipeTags(c.getInt(0));
		startManagingCursor(c2);
		if (c2.getCount() > 0) {
			do {
				dbAdapter.removeRecipeTag(c.getInt(0), c2.getInt(0));
				dbAdapter.deleteTagIfNoRecipe(c2.getInt(0));
			} while (c2.moveToNext());
		}
		dbAdapter.deleteRecipe(c.getInt(0));
		fillData();
		if (tagFilter == -1 && c.getCount() == 0) {
			TextView empty = (TextView) getListView().getEmptyView();
			empty.setText(R.string.recipelist_norecipe);
		}
		filterText(filterText.getText().toString());
	}

	@Override
	protected void onDestroy() {
		filterText.removeTextChangedListener(textWatcher);
		dbAdapter.close();
	    super.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putSerializable("filterText",
				filterText.getText().toString());
		outState.putSerializable("tagFilter", new Integer(tagFilter));
	}
}


text:
package org.traccar.events;

import java.util.ArrayList;
import java.util.Collection;

import org.traccar.BaseEventHandler;
import org.traccar.Context;
import org.traccar.model.Device;
import org.traccar.model.Event;
import org.traccar.model.Position;

public class OverspeedEventHandler extends BaseEventHandler {

    public static final String ATTRIBUTE_SPEED_LIMIT = "speedLimit";

    private boolean notRepeat;

    public OverspeedEventHandler() {
        notRepeat = Context.getConfig().getBoolean("event.overspeed.notRepeat");
    }

    @Override
    protected Collection<Event> analyzePosition(Position position) {

        Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId());
        if (device == null) {
            return null;
        }
        if (!Context.getIdentityManager().isLatestPosition(position) || !position.getValid()) {
            return null;
        }

        Collection<Event> events = new ArrayList<>();
        double speed = position.getSpeed();
        double speedLimit = Context.getDeviceManager()
                .lookupAttributeDouble(device.getId(), ATTRIBUTE_SPEED_LIMIT, 0, false);
        if (speedLimit == 0) {
            return null;
        }
        double oldSpeed = 0;
        if (notRepeat) {
            Position lastPosition = Context.getIdentityManager().getLastPosition(position.getDeviceId());
            if (lastPosition != null) {
                oldSpeed = lastPosition.getSpeed();
            }
        }
        if (speed > speedLimit && oldSpeed <= speedLimit) {
            events.add(new Event(Event.TYPE_DEVICE_OVERSPEED, position.getDeviceId(), position.getId()));
        }
        return events;
    }

}


text:
angular.
module('phoneList').
component('phoneList', {
    templateUrl: 'phone-list/phone-list.template.html',
    controller: ['$http',
        function PhoneListController($http) {
            var self = this;
            self.orderProp = 'age';

            $http.get('phones/phones.json').then(function(response) {
                self.phones = response.data.slice(0, 5);
            });
        }
    ]
});


text:
import { Core } from '../core';
import { Service } from '../service';
import { PathBuilder } from './path-builder';
import { PathCollectionBuilder } from './path-collection-builder';
import { UrlParamsBuilder } from './url-params-builder';
import { JsonapiBootstrap } from '../bootstraps/jsonapi-bootstrap';

const testService = new Service();
testService.getPrePath = (): string => {
    return 'test/pre-path';
};
testService.getPath = (): string => {
    return 'test/path';
};

describe('Path Builder', () => {
    let path_collection_builder = new PathCollectionBuilder();

    beforeAll(() => {
        JsonapiBootstrap.bootstrap({ user_config: { url: 'http://yourdomain/api/v1/' } });
    });
    it('should create', () => {
        expect(path_collection_builder).toBeTruthy();
    });
    it('applyParams method should call parent applyParams method with the provided parameters', () => {
        let applyParams_parent_spy = spyOn(PathBuilder.prototype, 'applyParams');
        path_collection_builder.applyParams(testService);
        expect(applyParams_parent_spy).toHaveBeenCalledWith(testService, {});
    });
    it('if remotefilters are provided and service has parseToServer method,\
     applyParams should call service s parseToServer method with them as parameter', () => {
        let parseToServer_spy = spyOn(testService, 'parseToServer');
        path_collection_builder.applyParams(testService, { remotefilter: { status: 'test_status' } });
        expect(parseToServer_spy).toHaveBeenCalledWith({ status: 'test_status' });
    });
    it('if service does not have parseToServer method, applyParams should not try to call this method', () => {
        let parseToServer_null_spy = spyOn(testService, 'parseToServer');
        testService.parseToServer = null;
        path_collection_builder.applyParams(testService, { remotefilter: { status: 'test_status' } });
        expect(parseToServer_null_spy).not.toHaveBeenCalled();
    });
    it('if remotefilters are provided, applyParams should call addParam with paramsurl.toparams result as parameter', () => {
        let addParam_parent_spy = spyOn<any>(path_collection_builder, 'addParam');
        let toparams_parent_spy = spyOn(UrlParamsBuilder.prototype, 'toparams');
        path_collection_builder.applyParams(testService, { remotefilter: { status: 'test_status' } });
        let test_params = new UrlParamsBuilder().toparams({ status: 'test_status' });
        expect(toparams_parent_spy).toHaveBeenCalledWith({ status: 'test_status' });
        expect(addParam_parent_spy).toHaveBeenCalledWith(test_params);
    });

    it('if fields are provided, they should be formatted and included in get_params', () => {
        path_collection_builder.applyParams(testService, { fields: { authors: ['name', 'address'], books: ['title'] } });
        expect(path_collection_builder.get().includes('fields[authors]=name,address&fields[books]=title')).toBeTruthy();
    });

    it('if filter with characters such as "&" are provided, they must be formatted and included in get_params', () => {
        path_collection_builder.applyParams(testService, { remotefilter: { field: 'foo&bar' } });
        expect(path_collection_builder.get().includes('filter[field]=foo%26bar')).toBeTruthy();
    });

    it('if page params are provided, applyParams should call addParam one or two times with the page number and size', () => {
        Core.me.injectedServices.rsJsonapiConfig.parameters.page.number = 'page_index';
        Core.me.injectedServices.rsJsonapiConfig.parameters.page.size = 'page_size';
        let addParam_parent_spy = spyOn<any>(path_collection_builder, 'addParam');
        path_collection_builder.applyParams(testService, { page: { number: 2 } });
        expect(addParam_parent_spy).toHaveBeenCalledTimes(1);
        expect(addParam_parent_spy).toHaveBeenCalledWith('page_index=2');
        path_collection_builder.applyParams(testService, { page: { number: 2, size: 10 } });
        expect(addParam_parent_spy).toHaveBeenCalledTimes(3);
        expect(addParam_parent_spy).toHaveBeenCalledWith('page_index=2');
        expect(addParam_parent_spy).toHaveBeenCalledWith('page_size=10');
    });
    it('if page number param is 1, applyParams should not call addParam with page number', () => {
        Core.me.injectedServices.rsJsonapiConfig.parameters.page.number = 'page_index';
        Core.me.injectedServices.rsJsonapiConfig.parameters.page.size = 'page_size';
        let addParam_parent_spy = spyOn<any>(path_collection_builder, 'addParam');
        path_collection_builder.applyParams(testService, { page: { number: 1 } });
        expect(addParam_parent_spy).not.toHaveBeenCalled();
        path_collection_builder.applyParams(testService, { page: { number: 1, size: 10 } });
        expect(addParam_parent_spy).toHaveBeenCalledTimes(1);
        expect(addParam_parent_spy).not.toHaveBeenCalledWith('page_number=1');
        expect(addParam_parent_spy).toHaveBeenCalledWith('page_size=10');
    });
    it('if sort params are provided, applyParams method should join the array with "," and call addParam with the resulting string', () => {
        let addParam_parent_spy = spyOn<any>(path_collection_builder, 'addParam');
        path_collection_builder.applyParams(testService, { sort: ['test', 'sort'] });
        expect(addParam_parent_spy).toHaveBeenCalledWith('sort=test,sort');
    });
    it('addParams method should push the provided string to the get_params array', () => {
        (path_collection_builder as any).get_params = [];
        (path_collection_builder as any).addParam('test_string');
        expect((path_collection_builder as any).get_params.length).toBe(1);
        expect((path_collection_builder as any).get_params).toEqual(['test_string']);
    });
    it('applyParams method should add the provided params to get_params array', () => {
        Core.me.injectedServices.rsJsonapiConfig.parameters.page.number = 'page_index';
        Core.me.injectedServices.rsJsonapiConfig.parameters.page.size = 'page_size';
        (path_collection_builder as any).get_params = [];
        path_collection_builder.applyParams(testService, { remotefilter: { status: 'test_status' }, page: { number: 2, size: 10 } });
        expect((path_collection_builder as any).get_params.length).toBe(3);
        expect((path_collection_builder as any).get_params).toEqual(['filter[status]=test_status', 'page_index=2', 'page_size=10']);
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="public">
  <uri id="User Entered Import Resolution" name="http://www.w3.org/2004/02/skos/core"
    uri="../W3C/core.owl"/>
</catalog>


text:
package org.apache.phoenix.end2end;

import static org.apache.phoenix.util.TestUtil.closeStmtAndConn;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Before;
import org.junit.Test;

public class LikeExpressionIT extends ParallelStatsDisabledIT {

    private String tableName;

    @Before
    public void initTable() throws Exception {
        tableName = generateUniqueName();
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DriverManager.getConnection(getUrl());
            String ddl;
            ddl = "CREATE TABLE " + tableName + " (k VARCHAR NOT NULL PRIMARY KEY, i INTEGER)";
            conn.createStatement().execute(ddl);
            insertRow(conn, "123n7-app-2-", 1);
            insertRow(conn, "132n7-App-2-", 2);
            insertRow(conn, "213n7-app-2-", 4);
            insertRow(conn, "231n7-App-2-", 8);
            insertRow(conn, "312n7-app-2-", 16);
            insertRow(conn, "321n7-App-2-", 32);
        } finally {
            closeStmtAndConn(stmt, conn);
        }
    }

    private void insertRow(Connection conn, String k, int i) throws SQLException {
        PreparedStatement stmt = conn.prepareStatement(
            "UPSERT INTO " + tableName + " VALUES (?, ?)");
        stmt.setString(1, k);
        stmt.setInt(2, i);
        stmt.executeUpdate();
        conn.commit();
    }

    private void testLikeExpression(Connection conn, String likeStr, int numResult, int expectedSum)
            throws Exception {
        String cmd = "select k, i from " + tableName + " where k like '" + likeStr + "'";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(cmd);
        int sum = 0;
        for (int i = 0; i < numResult; ++i) {
            assertTrue(rs.next());
            sum += rs.getInt("i");
        }
        assertFalse(rs.next());
        assertEquals(sum, expectedSum);
    }

    @Test
    public void testLikeExpression() throws Exception {
        Connection conn = DriverManager.getConnection(getUrl());
        // wildcard
        testLikeExpression(conn, "%1%3%7%2%", 3, 7);
        // CaseSensitive
        testLikeExpression(conn, "%A%", 3, 42);
        conn.close();
    }

    @Test
    public void testLikeEverythingExpression() throws Exception {
        Connection conn = DriverManager.getConnection(getUrl());
        String table = generateUniqueName();
        String ddl = "CREATE TABLE " + table
                + " (k1 VARCHAR, k2 VARCHAR, CONSTRAINT pk PRIMARY KEY (k1,k2))";
        conn.createStatement().execute(ddl);
        conn.createStatement().execute("UPSERT INTO " + table + " VALUES('aa','bb')");
        conn.createStatement().execute("UPSERT INTO " + table + " VALUES('ab','bc')");
        conn.createStatement().execute("UPSERT INTO " + table + " VALUES(null,'cc')");
        conn.createStatement().execute("UPSERT INTO " + table + " VALUES('dd',null)");
        conn.commit();

        ResultSet rs = conn.createStatement().executeQuery(
                "SELECT * FROM " + table + " WHERE k1 LIKE '%'");
        assertTrue(rs.next());
        assertEquals("aa", rs.getString(1));
        assertEquals("bb", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("ab", rs.getString(1));
        assertEquals("bc", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("dd", rs.getString(1));
        assertEquals(null, rs.getString(2));
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery("SELECT * FROM " + table + " WHERE k2 LIKE '%'");
        assertTrue(rs.next());
        assertEquals(null, rs.getString(1));
        assertEquals("cc", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("aa", rs.getString(1));
        assertEquals("bb", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("ab", rs.getString(1));
        assertEquals("bc", rs.getString(2));
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery("SELECT * FROM " + table + " WHERE k2 LIKE '%%'");
        assertTrue(rs.next());
        assertEquals(null, rs.getString(1));
        assertEquals("cc", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("aa", rs.getString(1));
        assertEquals("bb", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("ab", rs.getString(1));
        assertEquals("bc", rs.getString(2));
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery("SELECT * FROM " + table + " WHERE k2 NOT LIKE '%'");
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery("SELECT * FROM " + table + " WHERE k2 NOT LIKE '%%'");
        assertFalse(rs.next());

        conn.close();
    }

    @Test
    public void testLikeWithEscapenLParen() throws Exception {
        Connection conn = DriverManager.getConnection(getUrl());
        String t = generateUniqueName();
        String ddl = "CREATE TABLE " + t + " (k VARCHAR, v VARCHAR, CONSTRAINT pk PRIMARY KEY (k))";
        conn.createStatement().execute(ddl);
        conn.createStatement().execute("UPSERT INTO " + t + " VALUES('aa','bb')");
        conn.createStatement().execute("UPSERT INTO " + t + " VALUES('a\\(d','xx')");
        conn.createStatement().execute("UPSERT INTO " + t + " VALUES('dd',null)");
        conn.commit();

        ResultSet rs = conn.createStatement().executeQuery(
            "SELECT * FROM " + t + " WHERE k not like '%\\(%'");
        assertTrue(rs.next());
        assertEquals("aa", rs.getString(1));
        assertEquals("bb", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("dd", rs.getString(1));
        assertEquals(null, rs.getString(2));
        assertFalse(rs.next());
    }

    @Test
    public void testNewLine() throws Exception {
        Connection conn = DriverManager.getConnection(getUrl());
        String t = generateUniqueName();
        String ddl = "CREATE TABLE " + t + " (k VARCHAR NOT NULL PRIMARY KEY)";
        conn.createStatement().execute(ddl);
        conn.createStatement().execute("UPSERT INTO " + t + " VALUES('AA\nA')");
        conn.commit();

        ResultSet rs = conn.createStatement().executeQuery(
                "SELECT * FROM " + t + " WHERE k like 'AA%'");
        assertTrue(rs.next());
        assertEquals("AA\nA", rs.getString(1));

        rs = conn.createStatement().executeQuery(
                "SELECT * FROM " + t + " WHERE k like 'AA_A'");
        assertTrue(rs.next());
        assertEquals("AA\nA", rs.getString(1));

        rs = conn.createStatement().executeQuery(
                "SELECT * FROM " + t + " WHERE k like 'AA%A'");
        assertTrue(rs.next());
        assertEquals("AA\nA", rs.getString(1));

        rs = conn.createStatement().executeQuery(
                "SELECT * FROM " + t + " WHERE k like 'AA_'");
        assertFalse(rs.next());
    }

    @Test
    public void testOneChar() throws Exception {
        Connection conn = DriverManager.getConnection(getUrl());
        String t = generateUniqueName();
        String ddl = "CREATE TABLE " + t + " (k VARCHAR NOT NULL PRIMARY KEY)";
        conn.createStatement().execute(ddl);
        conn.createStatement().execute("UPSERT INTO " + t + " VALUES('A')");
        conn.createStatement().execute("UPSERT INTO " + t + " VALUES('AA')");
        conn.commit();

        ResultSet rs = conn.createStatement().executeQuery(
                "SELECT * FROM " + t + " WHERE k like '_'");
        assertTrue(rs.next());
        assertEquals("A", rs.getString(1));
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery(
                "SELECT * FROM " + t + " WHERE k like '_A'");
        assertTrue(rs.next());
        assertEquals("AA", rs.getString(1));
        assertFalse(rs.next());
    }

    @Test
    public void testNull() throws Exception {
        Connection conn = DriverManager.getConnection(getUrl());
        String table = generateUniqueName();
        String ddl = "CREATE TABLE " + table
                + " (pk INTEGER PRIMARY KEY, str VARCHAR)";
        conn.createStatement().execute(ddl);
        conn.createStatement().execute("UPSERT INTO " + table + " VALUES(0,'aa')");
        conn.createStatement().execute("UPSERT INTO " + table + " VALUES(1, null)");
        conn.commit();

        ResultSet rs = conn.createStatement().executeQuery(
                "SELECT str LIKE '%' FROM " + table);
        assertTrue(rs.next());
        assertEquals(true, rs.getBoolean(1));
        assertFalse(rs.wasNull());
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertTrue(rs.wasNull());
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery(
                "SELECT str LIKE '%%' FROM " + table);
        assertTrue(rs.next());
        assertEquals(true, rs.getBoolean(1));
        assertFalse(rs.wasNull());
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertTrue(rs.wasNull());
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery(
                "SELECT str NOT LIKE '%' FROM " + table);
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertFalse(rs.wasNull());
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertTrue(rs.wasNull());
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery(
                "SELECT str NOT LIKE '%%' FROM " + table);
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertFalse(rs.wasNull());
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertTrue(rs.wasNull());
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery(
                "SELECT NOT (str LIKE '%') FROM " + table);
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertFalse(rs.wasNull());
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertTrue(rs.wasNull());
        assertFalse(rs.next());

        rs = conn.createStatement().executeQuery(
                "SELECT NOT(str LIKE '%%') FROM " + table);
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertFalse(rs.wasNull());
        assertTrue(rs.next());
        assertEquals(false, rs.getBoolean(1));
        assertTrue(rs.wasNull());
        assertFalse(rs.next());
    }

    @Test
    public void testMultiCFLikeExpressionWithLimitOffset() throws Exception {
        String tableName = generateUniqueName();
        String ddl =
                "create table " + tableName
                        + " (id integer not null primary key, cf.col1 varchar, cf.col2 varchar, cf2.col3 varchar, cf2.col4 varchar)";
        String upsert = "UPSERT INTO " + tableName + " VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(getUrl())) {
            conn.createStatement().execute(ddl);
            PreparedStatement stmt = conn.prepareStatement(upsert);
            for (int i = 1; i <= 10; i++) {
                stmt.setInt(1, i);
                stmt.setString(2, i + "col1");
                stmt.setString(3, i + "col2");
                stmt.setString(4, i + "col3");
                stmt.setString(5, i + "col4");
                stmt.executeUpdate();
            }
            conn.commit();

            String query =
                    "select cf.* from " + tableName
                            + " where cf.col1 like '%col1%' limit 10 offset 2";
            ResultSet rs = conn.createStatement().executeQuery(query);
            int expectedCount = 8;
            int i = 0;
            while (rs.next()) {
                i++;
                assertTrue(rs.getString("COL1").contains("col1"));
                assertTrue(rs.getString("COL2").contains("col2"));
            }
            assertEquals(expectedCount, i);

            query =
                    "select cf.*, cf2.* from " + tableName
                            + " where cf.col1 like '%col1%' limit 10 offset 2";
            rs = conn.createStatement().executeQuery(query);
            i = 0;
            while (rs.next()) {
                i++;
                assertTrue(rs.getString("COL1").contains("col1"));
                assertTrue(rs.getString("COL2").contains("col2"));
                assertTrue(rs.getString("COL3").contains("col3"));
                assertTrue(rs.getString("COL4").contains("col4"));
            }
            assertEquals(expectedCount, i);
            query = "select * from " + tableName + " where cf.col1 like '%col1%' limit 10 offset 2";
            rs = conn.createStatement().executeQuery(query);
            i = 0;
            while (rs.next()) {
                i++;
                assertTrue(rs.getString("COL1").contains("col1"));
                assertTrue(rs.getString("COL2").contains("col2"));
                assertTrue(rs.getString("COL3").contains("col3"));
                assertTrue(rs.getString("COL4").contains("col4"));
            }
            assertEquals(expectedCount, i);
        }
    }

    @Test
    public void testSingleCFLikeExpressionWithLimitOffset() throws Exception {
        String tableName = generateUniqueName();
        String ddl =
                "create table " + tableName
                        + " (id integer not null primary key, cf.col1 varchar, cf.col2 varchar, cf.col3 varchar, cf.col4 varchar)";
        String upsert = "UPSERT INTO " + tableName + " VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(getUrl())) {
            conn.createStatement().execute(ddl);
            PreparedStatement stmt = conn.prepareStatement(upsert);
            for (int i = 1; i <= 10; i++) {
                stmt.setInt(1, i);
                stmt.setString(2, i + "col1");
                stmt.setString(3, i + "col2");
                stmt.setString(4, i + "col3");
                stmt.setString(5, i + "col4");
                stmt.executeUpdate();
            }
            conn.commit();

            String query =
                    "select cf.* from " + tableName
                            + " where cf.col1 like '%col1%' limit 10 offset 2";
            ResultSet rs = conn.createStatement().executeQuery(query);
            int expectedCount = 8;
            int i = 0;
            while (rs.next()) {
                i++;
                assertTrue(rs.getString("COL1").contains("col1"));
                assertTrue(rs.getString("COL2").contains("col2"));
            }
            assertEquals(expectedCount, i);

            query =
                    "select cf.* from " + tableName
                            + " where cf.col1 like '%col1%' limit 10 offset 2";
            rs = conn.createStatement().executeQuery(query);
            i = 0;
            while (rs.next()) {
                i++;
                assertTrue(rs.getString("COL1").contains("col1"));
                assertTrue(rs.getString("COL2").contains("col2"));
                assertTrue(rs.getString("COL3").contains("col3"));
                assertTrue(rs.getString("COL4").contains("col4"));
            }
            assertEquals(expectedCount, i);
            query = "select cf.* from " + tableName + " where cf.col1 like '%col1%' limit 10 offset 2";
            rs = conn.createStatement().executeQuery(query);
            i = 0;
            while (rs.next()) {
                i++;
                assertTrue(rs.getString("COL1").contains("col1"));
                assertTrue(rs.getString("COL2").contains("col2"));
                assertTrue(rs.getString("COL3").contains("col3"));
                assertTrue(rs.getString("COL4").contains("col4"));
            }
            assertEquals(expectedCount, i);
        }
    }

    @Test
    public void testParameterizedLikeExpression() throws Exception {
        final Connection conn = DriverManager.getConnection(getUrl());
        final PreparedStatement select = conn.prepareStatement(
                "select k from " + tableName + " where k like ?");
        select.setString(1, "12%");
        ResultSet rs = select.executeQuery();
        assertTrue(rs.next());
        assertEquals("123n7-app-2-", rs.getString(1));
        assertFalse(rs.next());

        select.setString(1, null);
        rs = select.executeQuery();
        assertFalse(rs.next());
    }
    //associated to PHOENIX-5173 jira
    @Test
    public void testLikeExpressionWithoutWildcards() throws Exception {
        String table = generateUniqueName();
        final String createTable = "CREATE TABLE "
                + table + " (ID BIGINT NOT NULL PRIMARY KEY, USER_NAME VARCHAR(255))";
        final String upsertTable = "UPSERT INTO " + table + " VALUES(1, 'Some Name')";
        String likeSelect = "SELECT * FROM " + table + " WHERE USER_NAME LIKE 'Some Name'";
        String iLikeSelect = "SELECT * FROM " + table + " WHERE USER_NAME ILIKE 'soMe nAme'";

        try(Connection conn = DriverManager.getConnection(getUrl())) {
            conn.setAutoCommit(true);
            conn.createStatement().execute(createTable);
            conn.createStatement().executeUpdate(upsertTable);
            try(ResultSet rs = conn.createStatement().executeQuery(likeSelect)) {
                assertTrue(rs.next());
                assertFalse(rs.next());
            }
            try(ResultSet rs = conn.createStatement().executeQuery(iLikeSelect)) {
                assertTrue(rs.next());
                assertFalse(rs.next());
            }
        }
    }
}


text:
define(['app/boot'], function (boot) {
    'use strict';
    boot.directive('theme', [
        function () {
            var _link = function ($scope, $element, $attrs, $ctrl) { };
            var _controller = function ($scope, $element, $attrs, $appEnvironment) {
                $scope.$appEnvironment = $appEnvironment;
            };
            return {
                scope: {
                    normal: '@',
                    path: '@'
                },
                restrict: 'AE',
                replace: true,
                link: _link,
                controller: [
                    '$scope',
                    '$element',
                    '$attrs',
                    '$appEnvironment',
                    _controller
                ],
                template: '<link ng-href="{{path}}/{{$appEnvironment.theme?$appEnvironment.theme:normal}}.css" rel="stylesheet" />'
            };
        }
    ]);
});
//# sourceMappingURL=theme.js.map