text:
/*global define */
define([
    'jquery',
    'text!ap-dataEntry/index.html',
    'underscore','bootstrap','handlebars',
    'js/renderAuthMenu',
    //'js/renderForm',
    'fx-common/jsonForm',
    'js/renderFormCustomFeature',
    'js/storeForm',
    'config/services',
    'ap-dataEntry/schemaUtils',
    'ap-dataEntry/dataEntryVariables',
    'calculated_values_algorithms/typeOfChangeField',
    'fx-common/fx-upload-client',
    'calculated_values_algorithms/policyDataObject',
    'amplify',
    'domready!'
], function ($, DataEntryTemplate, _, bootstrap, Handlebars,
             renderAuthMenu,
             renderForm,
             renderFormCustomFeature,
             storeForm,
             Config,
             SchemaUtils, DataEntryVariables, TypeOfChangeField, Uploader, ap_policyDataObject) {
            // SchemaUtils, DataEntryVariables, TypeOfChangeField) {

    var o = {
        dataEntryVariables : '',
        base_ip_address: '',
        base_ip_port: '',
        datasource: '',
        dataManagementToolObj: '',
        UPLOAD_CONTAINER: '#uploader-container',
        events : {
            event_prefix: "fx.upload.",
            FINISH: "finish"
            //self.o.event_prefix + "finish"
        },
        link_pdf_file_count :0,
        url : {
            savePdfUploadInfo_url : '/wdspolicy/rest/policyservice/dataManagementTool/savePdfUploadInfo',
            deletePdfUploadInfo_url : '/wdspolicy/rest/policyservice/dataManagementTool/deletePdfFile'
        },
        p : function(obj){
                //Deleting file with its metadata
                //http://fenixservices.fao.org/upload/file/policy/<md5>

                $.ajax({
                    type: 'GET',
                    url :   'http://fenixservices.fao.org/upload/file/policy/'+obj.item.details.md5,
                    //dataType: 'json',

                    success : function(response) {

                        console.log("After deleting file")
                        console.log(o)

                        var url = 'http://'+o.base_ip_address +':'+o.base_ip_port + o.url.savePdfUploadInfo_url;
                        var data = ap_policyDataObject.init();

                        data.loggedUser = o.dataManagementToolObj.LOGGED_USER;
                        if (o.fileName == "searchAddPolicy"){
                            data.saveAction = "ADD";
                        }
                        else{
                            data.saveAction = "EDIT";
                        }

                        data.datasource = o.datasource;
                        data.policy_id = o.policyId;
                        data.fileName = obj.item.file.name;
                        data.md5 = obj.item.details.md5;

                        var payloadrest = JSON.stringify(data);
                        $.ajax({
                            type: 'POST',
                            url: url,
                            data: {"pdObj": payloadrest},

                            success: function (response) {

                                //Database Update
                                console.log(response);
                                //Insert file name in the file list
                                var uploadTableElement = document.getElementById("uploadFileTable");
                                if((uploadTableElement!=null)&&(typeof uploadTableElement!= 'undefined')){
                                    //Check if there is already a file with that name
                                    //In the directory the file is overwritten
                                    //In the database the name is not added if that name was already stored
                                    //In the table of the interface the name of the file has not be added
                                    if((uploadTableElement.childNodes!=null)&&(typeof uploadTableElement.childNodes != 'undefined')){
                                        var len = uploadTableElement.childNodes.length;
                                        console.log(len)
                                        o.link_pdf_file_count = len;
                                        var i=0;
                                        for(i=0; i<len; i++){
                                            if((uploadTableElement.childNodes[i]!=null)&&(typeof uploadTableElement.childNodes[i]!='undefined')&&(uploadTableElement.childNodes[i].childNodes!=null)&&(typeof uploadTableElement.childNodes[i].childNodes!='undefined'))
                                                var value = uploadTableElement.childNodes[i].childNodes[0].innerHTML;
                                            if(response==value){
                                                //The name is already in the table
                                                break;
                                            }
                                        }
                                        if(i==len){
                                            //Not found
                                            //The name has to be inserted in the table
                                            var tr = document.createElement('tr');
                                            var td = document.createElement('td');
                                            var node = document.createTextNode(response);
                                            td.style = "width:70%";
                                            td.appendChild(node);
                                            tr.appendChild(td);
                                            td = document.createElement('td');
                                            var btn = document.createElement("BUTTON");        // Create a <button> element
                                            btn.setAttribute('fileName', response);
                                            data.policy_id = o.policyId;
                                            btn.setAttribute('policyId', data.policy_id);

                                            //btn.setAttribute('policyId', o.policyId);
                                            var t = document.createTextNode("Delete");       // Create a text node
                                            btn.onclick = function(){
                                                console.log(this.getAttribute('fileName'));
                                                console.log(this.getAttribute('policyId'));
                                                o.deleteFile(this);
                                                return false;
                                            };
                                            btn.appendChild(t);
                                            td.style = "width:30%";
                                            td.appendChild(btn);
                                            tr.appendChild(td);
                                            uploadTableElement.appendChild(tr);
                                            o.link_pdf_file_count++;
                                        }
                                    }
                                }
                                else{
                                    var tbl = document.createElement('table');
                                    tbl.className = 'table table-bordered';
                                    tbl.id = "uploadFileTable";
                                    var tr = document.createElement('tr');
                                    var td = document.createElement('td');
                                    var node = document.createTextNode(response);
                                    td.style = "width:70%";
                                    td.appendChild(node);
                                    tr.appendChild(td);
                                    td = document.createElement('td');
                                    var btn = document.createElement("BUTTON");        // Create a <button> element
                                    btn.setAttribute('fileName', response);
                                    //btn.setAttribute('policyId', o.policyId);
                                    data.policy_id = o.policyId;
                                    btn.setAttribute('policyId', data.policy_id);
                                    var t = document.createTextNode("Delete");       // Create a text node
                                    btn.onclick = function(){
                                        console.log(this.getAttribute('fileName'));
                                        o.deleteFile(this);
                                        return false;
                                    };
                                    btn.appendChild(t);
                                    td.style = "width:30%";
                                    td.appendChild(btn);
                                    tr.appendChild(td);
                                    tbl.appendChild(tr);
                                    document.getElementById("uploadFileTableContainer").appendChild(tbl);
                                    o.link_pdf_file_count=1;
                                }
                            },
                            error: function(err,b,c) {
                            }
                        });
                    },
                    error : function(err,b,c) {
                    }
                });
            },
        deleteFile : function(obj){
            if(o.link_pdf_file_count>1) {
                console.log("In...");
                obj.getAttribute('fileName');
                obj.getAttribute('policyId');

                var url = 'http://' + o.base_ip_address + ':' + o.base_ip_port + o.url.deletePdfUploadInfo_url;
                var data = ap_policyDataObject.init();

                data.loggedUser = o.dataManagementToolObj.LOGGED_USER;
                if (o.fileName == "searchAddPolicy") {
                    data.saveAction = "ADD";
                }
                else {
                    data.saveAction = "EDIT";
                }
                data.datasource = o.datasource;
                data.policy_id = obj.getAttribute('policyId');
                data.fileName = obj.getAttribute('fileName');

                var payloadrest = JSON.stringify(data);
                $.ajax({
                    type: 'POST',
                    url: url,
                    data: {"pdObj": payloadrest},

                    success: function (response) {
                        console.log("Deleting pdf file success");
                        o.link_pdf_file_count--;
                        var uploadTableElement = document.getElementById("uploadFileTable");
                        if((uploadTableElement!=null)&&(typeof uploadTableElement!= 'undefined')){
                            //In the table of the interface the name of the file is added
                            if((uploadTableElement.childNodes!=null)&&(typeof uploadTableElement.childNodes != 'undefined')){
                                var len = uploadTableElement.childNodes.length;
                                console.log(len)
                                var i=0;
                                for(i=0; i<len; i++){
                                    if((uploadTableElement.childNodes[i]!=null)&&(typeof uploadTableElement.childNodes[i]!='undefined')&&(uploadTableElement.childNodes[i].childNodes!=null)&&(typeof uploadTableElement.childNodes[i].childNodes!='undefined'))
                                        var value = uploadTableElement.childNodes[i].childNodes[0].innerHTML;
                                    if(data.fileName==value){
                                        //The name is in the table
                                        uploadTableElement.childNodes[i].remove();
                                        break;
                                    }
                                }
                            }
                        }
                    },
                    error: function (response) {
                        console.log("Deleting pdf file error");
                    }
                });
            }
        }
    };

    function Start(options) {
        $.extend(true, o, options);
        amplify.unsubscribe(o.events.event_prefix + o.events.FINISH, o.p);
    }

    Start.prototype.disableElements = function(){

        console.log(o);
        console.log(o.fileName);
        if(o.fileName== "searchEditPolicy"){
            //In Edit Policy there is at least one file linked
            //with the policy because this is a mandatory field
            console.log("Edit Before enable selection")
            //$(o.UPLOAD_CONTAINER).enableSelection();
            document.getElementById("uploader-container-summary").disabled=false;
            document.getElementById("fx-uploader-input").disabled=false;
        }
        else{
            console.log("Add Before disable selection")
            //$(o.UPLOAD_CONTAINER).disableSelection();
            //fx-uploader-input
            document.getElementById("uploader-container-summary").disabled=true;
            document.getElementById("fx-uploader-input").disabled=true;
        }
    };

    Start.prototype.init = function (options, dataManagementToolObj) {

        $.extend(true, o, options);
        console.log("START INIT")
        console.log(options)
        console.log(dataManagementToolObj)
        console.log("END INIT")
        var self = this;
        var dataEntryVariables = new DataEntryVariables();
        o.dataEntryVariables = dataEntryVariables;
        o.base_ip_address = options.base_ip_address;
        o.base_ip_port = options.base_ip_port;
        o.datasource = options.datasource;

        console.log(dataManagementToolObj)
        if(o.fileName =="searchEditPolicy"){
            o.policyId = dataManagementToolObj.policy_data.Policy_id;
            console.log(o.policyId)
        }
        o.dataManagementToolObj = dataManagementToolObj;

        $("#metadataEditorContainer").html(DataEntryTemplate);

        var authMenu =  renderAuthMenu('compile'),

        //TO REMOVE START
        //user = authMenu.auth.getCurrentUser();
        //user = {name: "" }
        user =  {
            "name" : "Guest",
            "password" : "guest"
        };
        //END TO REMOVE

        var formStore = new storeForm({
            prefix: user.name || 'unlogged',
            storeExpires: 100000,
            autosaveLoader: '#sectionstorage-loader'
        });

        id = "searchEditPolicy";
        if(o.fileName =="searchEditPolicy") {
            this.initUploadComponent(self);
        }
        if((options!=null)&&(typeof options!= "undefined")&&(options.fileName!=null)&&(typeof options.fileName!= "undefined")){

            //This is used to identify
            o.filename = options.fileName;
            //This is used to make the module undefined
            require.undef('ap-dataEntry/json/'+ options.fileName);
            require(['ap-dataEntry/json/'+ options.fileName ], function(schema) {

                var schemaUtils = new SchemaUtils();
                schemaUtils.init();
                schemaUtils.settingProperties(schema, options);
                renderFormCustomFeature('#'+ id, {
                    schema: schema,
                    iconlib: 'fontawesome4'
                });

                var disabled_fields = self.disabledOpenListFields(schema, dataEntryVariables, null);
                disabled_fields = self.disabledFields(schema, dataEntryVariables, disabled_fields);
                //console.log(JSON.stringify(schema))
                console.log("Before render form ")
                console.log(console.log(schema.properties));
                self.render = new renderForm('#'+ id, {
                    schema: schema,
                    iconlib: 'fontawesome4',
                    //theme: 'ap_dataEntry_theme',
                    theme: 'bootstrap3',
                    disable_array_add: true,
                    //disable_array_delete: true,
                    disable_array_reorder: true,
                    disabled:disabled_fields,
                    //values: formStore.getSections(),
                    tmpl: {reset :'', submit: 'Save'},
                    //tmpl: {reset :'', submit: ''},
                    onSubmit: function(data) {self.saveActionFunction(data,self, dataEntryVariables)},
                    onChange: function(data) {
                        //alert("onChange!!!");
                        //console.log('onChange',data)
                        console.log(self.render.editor.getValue())
                        var path = dataEntryVariables.options.policyElement_path;
                        var field = self.render.editor.getEditor(path);
                        console.log(field)
                        self.disableNameInOpenList(field, dataEntryVariables);
                        path = dataEntryVariables.options.unit_path;
                        var unit_field = self.render.editor.getEditor(path);
                        self.disableNameInOpenList(unit_field, dataEntryVariables);
                        path = dataEntryVariables.options.source_path;
                        field = self.render.editor.getEditor(path);
                        self.disableNameInOpenList(field, dataEntryVariables);
                        path = dataEntryVariables.options.secondGenerationSpecific_path;
                        field = self.render.editor.getEditor(path);
                        self.disableNameInOpenList(field, dataEntryVariables);
                        //path = dataEntryVariables.options.MinAVTariffValue_path;
                        //field = self.render.editor.getEditor(path);
                        //self.disableNameInOpenList(field, dataEntryVariables);
                        //Value and Value Text based on valueValueText selection
                        path = dataEntryVariables.options.valueValueText_path;
                        var valueValueTextField = self.render.editor.getEditor(path);
                        path = dataEntryVariables.options.value_path;
                        var valueField = self.render.editor.getEditor(path);
                        path = dataEntryVariables.options.valueText_path;
                        var ValueTextField = self.render.editor.getEditor(path);
                        self.valueValueTextChanged(valueValueTextField, valueField, ValueTextField, unit_field, dataEntryVariables);
                    },
                    onReady: function() {
                        if(options.fileName =="searchAddPolicy"){
                            console.log("SEARCH ADD POLICY START")
                            var path = dataEntryVariables.options.policyElement_path;
                            var field = self.render.editor.getEditor(path);
                            self.disableNameInOpenList(field, dataEntryVariables);
                            path = dataEntryVariables.options.unit_path;
                            var unit_field = self.render.editor.getEditor(path);
                            self.disableNameInOpenList(unit_field, dataEntryVariables);
                            path = dataEntryVariables.options.source_path;
                            field = self.render.editor.getEditor(path);
                            self.disableNameInOpenList(field, dataEntryVariables);
                            path = dataEntryVariables.options.secondGenerationSpecific_path;
                            field = self.render.editor.getEditor(path);
                            self.disableNameInOpenList(field, dataEntryVariables);
                            //path = dataEntryVariables.options.MinAVTariffValue_path;
                            //field = self.render.editor.getEditor(path);
                            //self.disableNameInOpenList(field, dataEntryVariables);
                            //self.render.editor.setValue({
                            //    linkPdfUpload: "/home/barbara/Documenti/"
                            //});

                            //Value and Value Text based on valueValueText selection
                            path = dataEntryVariables.options.valueValueText_path;
                            var valueValueTextField = self.render.editor.getEditor(path);
                            path = dataEntryVariables.options.value_path;
                            var valueField = self.render.editor.getEditor(path);
                            path = dataEntryVariables.options.valueText_path;
                            var ValueTextField = self.render.editor.getEditor(path);
                            self.valueValueTextChanged(valueValueTextField, valueField, ValueTextField, unit_field, dataEntryVariables);
                        }
                    }
                });
            }, function (err) {
            });
        }
    };

    Start.prototype.setPolicyId= function(policy_id){
        console.log("policy_id= "+policy_id);
        o.policyId = policy_id;
    };

    //Start.prototype.deleteFileFunct = function(fileName){
    //    alert("fileName = "+fileName);
    //    return false;
    //}

    //Start.prototype.initUploadComponent = function(data, self, dataEntryVariables){
    Start.prototype.initUploadComponent = function(self){
        console.log("In initUploadComponent start")
        console.log(self)
        //this.uploader = new Uploader({
        //    server_url: 'http://168.202.28.32:8080/v1',
        //    context: "policy"
        //});
        //
        //this.uploader.render({
        //    container : o.UPLOAD_CONTAINER,
        //    body_post_process : {
        //        policyId : "11",
        //        size: "@file.size",
        //        name: "@file.name"
        //    }
        //});

        var config = {
            container: o.UPLOAD_CONTAINER,
            context: "policy",
            //server_url: 'http://168.202.28.32:8080/v1',
            server_url: 'http://fenixservices.fao.org/upload',
            //body_post_process : { policy : "11", name: "@file.name"}
            //body_post_process : { policy : "12"},
            body_post_process : { policy : o.policyId},
            body_create_file : {
                size: "@file.size",
                name: "@file.name"
            }
        };

        this.uploader = new Uploader();

        if ((o.properties.linkPdf != null) && (typeof o.properties.linkPdf != "undefined")) {//OK
            if ((o.properties.linkPdf.value!=null)&&(typeof o.properties.linkPdf.value!="undefined")&&(o.properties.linkPdf.value.default!= null)&&(typeof o.properties.linkPdf.value.default!="undefined")) {
                var linkPdfArray = o.properties.linkPdf.value.default.split(';');
                var tbl = document.createElement('table');
                tbl.className = 'table table-bordered';
                tbl.id = "uploadFileTable";
                o.link_pdf_file_count=0;
                for(var i=0; i<linkPdfArray.length; i++){
                    console.log("Adding in table linkPdfArray "+linkPdfArray[i]);
                    //Removing white space at the start and at the end of each file name
                    var fileName = linkPdfArray[i].trim();
                    //Object creation
                    var tr = document.createElement('tr');
                    var td = document.createElement('td');
                   // td.data.value = fileName;
                    var node = document.createTextNode(fileName);
                    td.style = "width:70%";
                    td.appendChild(node);
                    tr.appendChild(td);
                    td = document.createElement('td');
                    var btn = document.createElement("BUTTON");        // Create a <button> element
                    btn.setAttribute('fileName', fileName);
                    btn.setAttribute('policyId', o.policyId);
                    var t = document.createTextNode("Delete");       // Create a text node
                    btn.onclick = function(){
                        console.log(this.getAttribute('fileName'));
                        o.deleteFile(this);
                        return false;
                    };
                    btn.appendChild(t);
                    td.style = "width:30%";
                    td.appendChild(btn);
                    tr.appendChild(td);
                    tbl.appendChild(tr);
                    o.link_pdf_file_count++;
                }
                document.getElementById("uploadFileTableContainer").appendChild(tbl);
            }
        }

        amplify.subscribe(o.events.event_prefix + o.events.FINISH, o.p);

        this.uploader.render(config);

        //Disable elements
        this.disableElements();
    };

    Start.prototype.saveActionFunction = function(data, self, dataEntryVariables){
        //LOGGED_USER contains "OECD" or "12"(Country code)
        console.log(data)
        console.log(self.render.editor.schema.properties)
        if(self.mandatoryFields(data, dataEntryVariables)){
            if(o.fileName =="searchAddPolicy"){
                //In this case the policy is not there
                //So "o.dataManagementToolObj.policy.policy_data" is empty
                var obj = {};
                obj.UPLOAD_CONTAINER = o.UPLOAD_CONTAINER;
                obj.startObj = self;
                obj.p = o.p;
                obj.deleteFile = o.deleteFile;
                obj.events = o.events;
                obj.editor_values = data;
                obj.base_ip_address = o.base_ip_address;
                obj.base_ip_port = o.base_ip_port;
                obj.datasource = o.datasource;
                obj.dataManagementToolObj = o.dataManagementToolObj;
                obj.dataManagementToolObj.policy_data = self.policyDataFieldCreation_byEditorValues(data,self);
                console.log("Before codeSettingInPolicyTable ")
                console.log(obj)
                console.log(obj.dataManagementToolObj.policy_data);
                self.codeSettingInPolicyTable(data, self, obj.dataManagementToolObj.policy_data);
                console.log("After codeSettingInPolicyTable ")
                console.log(obj.dataManagementToolObj.policy_data);
                obj.fileName = o.filename;
                console.log("DATA START ADD")
                console.log(data)
                console.log("DATA END ADD")
                console.log("OBJ START ADD")
                console.log(obj)
                console.log("OBJ END ADD")
                var typeOfChangeField = new TypeOfChangeField(obj, self);
                typeOfChangeField.init();
            }
            else if(o.fileName =="searchEditPolicy"){
                var obj = {};
                obj.editor_values = data;
                obj.base_ip_address = o.base_ip_address;
                obj.base_ip_port = o.base_ip_port;
                obj.datasource = o.datasource;
                console.log("In edit policy")
                console.log(o)
                console.log(o.policyId)
                obj.dataManagementToolObj = o.dataManagementToolObj;

                obj.dataManagementToolObj.policy_data = self.policyDataFieldCreation_byEditorValues(data,self);
                console.log(o.dataManagementToolObj)
                console.log(o)
                obj.dataManagementToolObj.policy_data.Policy_id = o.dataManagementToolObj.policy_data.Policy_id;
                obj.dataManagementToolObj.policy_data.Policy_id = o.policyId;
                console.log("Before codeSettingInPolicyTable ")
                console.log(o)
                console.log(obj.dataManagementToolObj.policy_data);
                self.codeSettingInPolicyTable(data, self, obj.dataManagementToolObj.policy_data);
                console.log("After codeSettingInPolicyTable ")
                console.log(obj.dataManagementToolObj.policy_data);

                obj.fileName = o.filename;
                console.log("DATA START")
                console.log(data)
                console.log("DATA END")
                console.log("OBJ START")
                console.log(obj)
                console.log("OBJ END")
                console.log(obj.dataManagementToolObj.policy_data);
                var typeOfChangeField = new TypeOfChangeField(obj);
                typeOfChangeField.init();
            }
        }
    };

    //This function is used in the Add Policy
    Start.prototype.policyDataFieldCreation_byEditorValues = function(data, self){
        var policyTableData = {};
        //policyElement
        //unit
        //source
        //secondGenerationSpecific
        //localCondition

        policyTableData.Link = data.link;
        policyTableData.LinkPdf = data.linkPdf;
        policyTableData.ValueText = '';
        policyTableData.Value = '';
        if(data.valueValueText == o.dataEntryVariables.options.valueValueText_enum_values[0]){
            //Value
            policyTableData.Value = data.value;
            policyTableData.ValueType = o.dataEntryVariables.options.valueValueText_enum_values[0];
        }
        else{
            //Value Text
            policyTableData.ValueText = data.valueText;
            policyTableData.ValueType = o.dataEntryVariables.options.valueValueText_enum_values[1];
        }
        policyTableData.Exemptions = data.exemptions;
        policyTableData.TaxRateBenchmark = data.taxRateBenchmark;
        policyTableData.BenchmarkLink = data.benchmarkLink;
        policyTableData.BenchmarkLinkPdf = data.benchmarkLinkPdf;
        policyTableData.Notes = data.notes;
        policyTableData.TitleOfNotice = data.titleOfNotice;
        policyTableData.LegalBasisName = data.legalBasisName;
        policyTableData.BenchmarkTax = data.benchmarkTax;
        policyTableData.BenchmarkProduct = data.benchmarkProduct;
        policyTableData.TaxRateBiofuel = data.taxRateBiofuel;
        policyTableData.MeasureDescription = data.measureDescription;
        policyTableData.ProductOriginalHs = data.productOriginalHs;
        policyTableData.ProductOriginalName = data.productOriginalName;
        policyTableData.PolicyElement = '';
        if((data.policyElement!=null)&&(typeof data.policyElement!='undefined')){
            if(data.policyElement.list==o.dataEntryVariables.options.OTHER){
                policyTableData.PolicyElement = data.policyElement.name;
            }
            else{
                policyTableData.PolicyElement = data.policyElement.list;
            }
        }

        policyTableData.Unit = '';
        if((data.unit!=null)&&(typeof data.unit!='undefined')){
            if(data.unit.list==o.dataEntryVariables.options.OTHER){
                policyTableData.Unit = data.unit.name;
            }
            else{
                policyTableData.Unit = data.unit.list;
            }
        }

        policyTableData.Source = data.source;
        if((data.source!=null)&&(typeof data.source!='undefined')&&(data.source.list==o.dataEntryVariables.options.OTHER)){
            policyTableData.Source = data.source.name;
        }
        else{
            policyTableData.Source = data.source.list;
        }
        policyTableData.SecondGenerationSpecific = '';
        if((data.secondGenerationSpecific!=null)&&(typeof data.secondGenerationSpecific!='undefined')){
            if(data.secondGenerationSpecific.list==o.dataEntryVariables.options.OTHER){
                policyTableData.SecondGenerationSpecific = data.secondGenerationSpecific.name;
            }
            else{
                policyTableData.SecondGenerationSpecific = data.secondGenerationSpecific.list;
            }
        }
        //policyTableData.MinAVTariffValue = "";
        //if((data.MinAVTariffValue!=null)&&(typeof data.MinAVTariffValue!='undefined')){
        //    if(data.MinAVTariffValue.list==o.dataEntryVariables.options.OTHER){
        //        policyTableData.MinAVTariffValue = data.MinAVTariffValue.name;
        //    }
        //    else{
        //        policyTableData.MinAVTariffValue = data.MinAVTariffValue.list;
        //    }
        //}
        policyTableData.MinAVTariffValue = data.MinAVTariffValue;
        policyTableData.MaxAVTariffValue = data.MaxAVTariffValue;
        policyTableData.CountAVTariff = data.CountAVTariff;
        policyTableData.CountNAVTariff = data.CountNAVTariff;
        policyTableData.StartDate = data.startDate;
        policyTableData.EndDate = data.endDate;

        policyTableData.DateOfPublication = data.dateOfPublication;
        policyTableData.StartDateTax = data.startDateTax;

        //These fields should be calculated
        //policyTableData.TypeOfChangeName = data.type_of_change_name;
        //policyTableData.ImposedEndDate = data.imposed_end_date;

        return policyTableData;
    };

    Start.prototype.mandatoryFields = function(data, dataEntryVariables){
        var ris= false;
        var errorString ='';
        if((data!=null)&&(typeof data!="undefined")){
            if((data.startDate!=null)&&(typeof data.startDate!="undefined")&&(data.startDate.length==10)){
                if((data.dateOfPublication!=null)&&(typeof data.dateOfPublication!="undefined")&&(data.dateOfPublication.length==10)){
                    if((data.link!=null)&&(typeof data.link!="undefined")&&(data.link.length>0)){
                        console.log(data)
                        ris = true;
                    }
                    else{
                        errorString+= 'Please, before saving complete the field: LINK';
                    }
                }
                else{
                    errorString+= 'Please, before saving complete the field: DATE OF PUBLICATION (in DD-MM-YYY format)';
                }
            }
            else{
                errorString = 'Please, before saving complete the field: START DATE (in DD-MM-YYY format)';
            }
        }
        if(document.getElementById(dataEntryVariables.options.mandatoryFieldsError)!=null){
            document.getElementById(dataEntryVariables.options.mandatoryFieldsError).remove();
        }
        if(ris==false){
            //".fx-jsonform"
            $(dataEntryVariables.options.dataEntryToolClassDiv).append("<div id="+dataEntryVariables.options.mandatoryFieldsError+">"+errorString+"</div>");
        }
        return ris;
    };

    //This is the original
    //Start.prototype.lastMandatoryFields = function(data, dataEntryVariables){
    //    var ris= false;
    //    var errorString ='';
    //    if((data!=null)&&(typeof data!="undefined")){
    //        if((data.startDate!=null)&&(typeof data.startDate!="undefined")&&(data.startDate.length==10)){
    //            if((data.dateOfPublication!=null)&&(typeof data.dateOfPublication!="undefined")&&(data.dateOfPublication.length==10)){
    //                console.log(data)
    //                console.log(data.link)
    //                console.log(data.linkPdf)
    //                if((data.link!=null)&&(typeof data.link!="undefined")&&(data.link.length>0)){
    //                    if((data.linkPdf!=null)&&(typeof data.linkPdf!="undefined")&&(data.linkPdf.length>0)){
    //                        ris = true;
    //                    }
    //                    else{
    //                        errorString+= 'Please, before saving fill: LINK PDF';
    //                    }
    //                }
    //                else{
    //                    errorString+= 'Please, before saving fill: LINK';
    //                }
    //            }
    //            else{
    //                errorString+= 'Please, before saving fill: DATE OF PUBLICATION (in DD-MM-YYY format)';
    //            }
    //        }
    //        else{
    //            errorString = 'Please, before saving fill: START DATE (in DD-MM-YYY format)';
    //        }
    //    }
    //    if(document.getElementById(dataEntryVariables.options.mandatoryFieldsError)!=null){
    //        document.getElementById(dataEntryVariables.options.mandatoryFieldsError).remove();
    //    }
    //    if(ris==false){
    //        //".fx-jsonform"
    //        $(dataEntryVariables.options.dataEntryToolClassDiv).append("<div id="+dataEntryVariables.options.mandatoryFieldsError+">"+errorString+"</div>");
    //    }
    //    return ris;
    //};

    Start.prototype.valueValueTextChanged = function (valueValueTextField, valueField, ValueTextField, unit_field, dataEntryVariables) {
        if((valueValueTextField!=null)&&(typeof valueValueTextField!="undefined")){
            var valueText = valueValueTextField.getValue();
            switch (valueText){
                case o.dataEntryVariables.options.valueValueText_enum_values[0]:
                    //Value
                    //Disable Value Text
                    //ValueTextField.setValue("");
                    ValueTextField.disable();
                    //Enable Value and Unit
                    valueField.enable();
                    if(unit_field.getValue().list==dataEntryVariables.options.OTHER){
                        unit_field.editors.name.enable();
                    }
                    unit_field.editors.list.enable();
                    break;
                case o.dataEntryVariables.options.valueValueText_enum_values[1]:
                    //Value Text
                    //Disable Value and Unit
                    //valueField.setValue("");
                    valueField.disable();
                    //unit_field.editors.name.setValue("");
                    unit_field.editors.name.disable();
                    //unit_field.editors.list.setValue("");
                    unit_field.editors.list.disable();
                    //Enable Value Text
                    ValueTextField.enable();
                    break;
                default : break;
            }
        }
    };

    Start.prototype.disableNameInOpenList = function (field, dataEntryVariables) {
        if((field!=null)&&(typeof field!="undefined")){
            var value = field.getValue().list;
            if((value!=null)&&(typeof value !="undefined")){
                if(value==dataEntryVariables.options.OTHER){
                    field.editors.name.enable();
                }
                else{
                    //Empty Name
                    field.editors.name.setValue("");
                    field.editors.name.disable();
                }
            }
        }
    };

    //This function is used to store the content of each enum in the form
    Start.prototype.codeSettingInPolicyTable = function (data, self, policyTableData) {
        console.log("saveName start")
        console.log(data)
        console.log(self)
        //Policy Element has to be considered
        //Loop on the array and create a new code greather than the last and smaller than '99'='n.a.'
        //If it'98 jumps to 100
        var listToCheck = o.dataEntryVariables.options.openListfieldsToDisable;
        //["policyElement", "unit", "source", "secondGenerationSpecific", "localCondition"]
        //Setting the codes to store in the database
        var field = data.policyElement;
        if((field!=null)&&(typeof field!='undefined')){
            var policyElement = self.render.opts.schema.properties.policyElement;
            var policyElementTitlesArray = policyElement.properties.list.options.enum_titles;
            if(data.policyElement.list==o.dataEntryVariables.options.OTHER){
                //The element is new
                policyTableData.PolicyElement = data.policyElement.name;
                var maxCode = parseInt(policyElement.properties.list.enum[0],10);
                for(var i=1;i<policyElement.properties.list.enum.length; i++){
                    if((policyElement.properties.list.enum[i]>maxCode)&&(policyElement.properties.list.enum[i]!='99')){
                        maxCode = parseInt(policyElement.properties.list.enum[i],10);
                    }
                }
                if(maxCode== 99){
                    //The new code cannot be set like '99' because it's used for none code
                    maxCode=100;
                }
                policyTableData.ElementCode = maxCode;
            }
            else{
                //The element is already in the list
                policyTableData.PolicyElement = data.policyElement.list;

                var indexEl = $.inArray(policyTableData.PolicyElement, policyElementTitlesArray);
                policyTableData.ElementCode = policyElement.properties.list.enum[indexEl];
            }
        }

        //Setting the ids
        //metadata_id                | integer                |
        //policy_id                  | integer                |
        //cpl_id                     | integer                |
        //commodity_id               | double precision       |
        //type_of_change_code        | double precision       |//Calculated by the algo
        //element_code               | integer                |

        policyTableData.CommodityId = o.dataManagementToolObj.master_data.CommodityId;
        policyTableData.CplId = o.dataManagementToolObj.master_data.CplId;
    };

    Start.prototype.disabledOpenListFields = function (schema, dataEntryVariables, disabledElementArray) {
        var disabledElement = [];
        if(disabledElementArray!=null){
            disabledElement = disabledElementArray;
        }

        var toCheck = dataEntryVariables.options.openListfieldsToDisable;
        for(var i=0; i<toCheck.length; i++){
            var fieldName = toCheck[i];
            if((schema.properties[fieldName]!=null)&&(typeof schema.properties[fieldName]!= "undefined")){
                disabledElement.push(fieldName+'.name');
            }
        }
        return disabledElement;
    };

    Start.prototype.disabledFields = function (schema, dataEntryVariables, disabledElementArray) {
        var disabledElement = [];
        if(disabledElementArray!=null){
            disabledElement = disabledElementArray;
        }

        var toCheck = dataEntryVariables.options.fieldsToDisable;
        for(var i=0; i<toCheck.length; i++){
            var fieldName = toCheck[i];
            if((schema.properties[fieldName]!=null)&&(typeof schema.properties[fieldName]!= "undefined")){
                disabledElement.push(fieldName);
            }
        }
        return disabledElement;
    };

    Start.prototype.getValues = function () {
        return this.controller.getValues();
    };

    Start.prototype.add = function (modules, adapterMap) {

        this.controller.add(modules, adapterMap);
    };

    return Start;
});


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.hyperledger.core.bitcoin;

import org.hyperledger.HyperLedgerSettings;
import org.hyperledger.common.*;
import org.hyperledger.common.color.Color;
import org.hyperledger.common.color.ColoredTransactionOutput;
import org.hyperledger.core.*;
import org.hyperledger.core.signed.BlockSignatureConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class BitcoinMiner implements Runnable, BlockStore.BlockListener {
    private static final Logger log = LoggerFactory.getLogger(BitcoinMiner.class);

    private final BlockStore store;
    private MiningConfig miningConfig;
    private final BitcoinValidatorConfig config;
    private final BlockSignatureConfig blockSignatureConfig;
    private Address minerAddress;
    private volatile boolean running = true;
    private AtomicBoolean abortMiningNextBlock = new AtomicBoolean(false);

    public BitcoinMiner(BlockStore store, MiningConfig miningConfig, BitcoinValidatorConfig config, BlockSignatureConfig blockSignatureConfig) {
        this.store = store;
        this.miningConfig = miningConfig;
        this.config = config;
        this.blockSignatureConfig = blockSignatureConfig;
        minerAddress = miningConfig.getMinerAddress();
        store.addBlockListener(this);
    }

    @Override
    public void run() {
        mineContinuously();
    }

    public void start() {
        running = true;
        abortMiningNextBlock.set(false);
        Thread minerThread = new Thread(this, "MinerThread");
        // set slightly lower priority to give yield to getting/storing new blocks from hte network
        minerThread.setPriority(Thread.NORM_PRIORITY - 1);
        minerThread.start();
    }

    public void stop() {
        running = false;
    }

    public void mineContinuously() {
        log.info("Mining started, delay between blocks {} sec", miningConfig.getDelayBetweenMiningBlocksSecs());
        try {
            while (running) {
                try {
                    long miningStartTime = System.currentTimeMillis();
                    mineAndStoreOneBlock();
                    if (miningConfig.getDelayBetweenMiningBlocksSecs() > 0) {
                        long miningTimeMillis = System.currentTimeMillis() - miningStartTime;
                        sleep(Math.max(0, 1000 * miningConfig.getDelayBetweenMiningBlocksSecs() - miningTimeMillis));
                    }
                } catch (HyperLedgerException e) {
                    log.error("Mining error: {}", e.getMessage());
                    sleep(1000);
                }
            }
        } finally {
            log.info("Mining stopped");
            running = false;
        }
    }

    public Block mineAndStoreOneBlock() throws HyperLedgerException {
        Block block = mineOneBlock();
        if (block != null) {
            store.addClientBlock(block);
        }
        return block;
    }

    public Block mineOneBlock() throws HyperLedgerException {
        abortMiningNextBlock.set(false);
        Block block;
        StoredBlock previous = store.getHighestBlock();
        int intendedHeight = previous.getHeight() + 1;
        log.info("Attempting mining the next block at h: {}, p: {}", intendedHeight, previous.getID());

        int target = previous.getHeader().getEncodedDifficulty();
        if ((previous.getHeight() + 1) % config.getReviewBlocks() == 0 && previous.getHeight() + 1 > config.getReviewBlocks()) {
            target = config.getDifficulty().computeNextDifficulty(store, previous.getHeader());
            log.info("New difficulty target: {} at height: {}", String.format("%x", target), previous.getHeight() + 1);
        }

        if (blockSignatureConfig.enabled()) {
            block = mineWithBlockSignature(previous, target, minerAddress);
        } else {
            block = mineRegular(previous, target, minerAddress);
        }
        if (block != null) {
            log.info("Mined block, id: {}, intended h: {}, ct: {}, d: {}, p: {}", block.getID(), intendedHeight, block.getLocalCreateTime(), block.getDifficultyTarget(), block.getPreviousID());
        } else {
            log.info("Mining a single block aborted, intended h: {}, p: {}", intendedHeight, previous.getID());
        }
        return block;
    }

    private Block mineRegular(StoredBlock previous, int target, Address minerAddress) throws HyperLedgerException {
        if (abortMiningNextBlock.compareAndSet(true, false) || !running) return null;
        while (true) {
            int createTime = calculateNextCreateTime(previous);
            List<Transaction> include = collectTransactions(previous, minerAddress);
            MerkleRoot root = MerkleTree.computeMerkleRoot(include);
            for (int nonce = Integer.MIN_VALUE; nonce < Integer.MAX_VALUE; ++nonce) {
                if (abortMiningNextBlock.compareAndSet(true, false) || !running) {
                    return null;
                }
                BitcoinHeader header = new BitcoinHeader(config.getNewBlockVersion(), previous.getID(), root, createTime, target, nonce);
                if (header.getID().toBigInteger().compareTo(BitcoinDifficulty.getTarget(target)) <= 0) {
                    return new Block(header, include);
                }
            }
        }
    }

    private Block mineWithBlockSignature(StoredBlock previous, int target, Address minerAddress) throws HyperLedgerException {
        if (abortMiningNextBlock.compareAndSet(true, false) || !running) return null;
        byte[] script = Script.create().blockSignature(blockSignatureConfig.getRequiredSignatureCount(), blockSignatureConfig.getPublicKeys()).build().toByteArray();
        byte[] scriptHash = Hash.keyHash(script);
        while (true) {
            int createTime = calculateNextCreateTime(previous);
            List<Transaction> include = collectTransactions(previous, minerAddress);
            MerkleRoot root = MerkleTree.computeMerkleRoot(include);
            for (int nonce = Integer.MIN_VALUE; nonce < Integer.MAX_VALUE; ++nonce) {
                if (abortMiningNextBlock.compareAndSet(true, false) || !running) {
                    return null;
                }
                BitcoinHeader header = new BitcoinHeader(config.getNewBlockVersion(), previous.getID(), root, createTime, target, nonce);
                Script inScript = calculateInScript(header, script);
                HeaderWithSignatures headerWithSignatures = new HeaderWithSignatures(config.getNewBlockVersion(), previous.getID(), root, createTime, target, nonce, inScript, scriptHash);
                if (headerWithSignatures.getID().toBigInteger().compareTo(BitcoinDifficulty.getTarget(target)) <= 0) {
                    return new Block(headerWithSignatures, include);
                }
            }
        }
    }

    @SuppressWarnings("deprecation")
    private int calculateNextCreateTime(StoredBlock previous) {
        int createTime = (int) (new Date().getTime() / 1000);
        if (createTime <= previous.getCreateTime()) {
            // Note that this can generate a timestamp too far in the future if we mine too fast.  But it should
            // be fine if we average one per second.  This is nicer for local testing, so that we don't take two
            // minutes to initialize a chain.
            createTime = previous.getCreateTime() + 1;
        }
        return createTime;
    }

    private Script calculateInScript(BitcoinHeader header, byte[] script) {
        ScriptBuilder scriptBuilder = Script.create();
        for (int i = 0; i < blockSignatureConfig.getPrivateKeyIndex(); i++) {
            scriptBuilder.data(new byte[0]);
        }
        try {
            byte[] sign = blockSignatureConfig.getMinerPrivateKey().sign(Hash.keyHash(header.toByteArray()));
            scriptBuilder.data(sign);
        } catch (IOException e) {
            // should not happen
        }
        for (int i = blockSignatureConfig.getPrivateKeyIndex() + 1; i < blockSignatureConfig.getPublicKeys().size(); i++) {
            scriptBuilder.data(new byte[0]);
        }
        return scriptBuilder.data(script).build();
    }

    private List<Transaction> collectTransactions(StoredBlock previous, Address minerAddress) throws HyperLedgerException {
        WireFormat.SizeWriter sizeWriter = new WireFormat.SizeWriter();
        WireFormatter wireFormatter = HyperLedgerSettings.getInstance().getTxWireFormatter();
        int height = previous.getHeight() + 1;
        Transaction coinbase = createCoinbase(height, minerAddress, config.getRewardForHeight(height));
        List<Transaction> include = new ArrayList<>();
        try {
            wireFormatter.toWire(coinbase, sizeWriter);
            Iterator<ValidatedTransaction> transactionList = store.getMempoolContent().iterator();

            long fee = 0;
            include.add(coinbase);
            while (transactionList.hasNext()) {
                ValidatedTransaction transaction = transactionList.next();
                wireFormatter.toWire(transaction, sizeWriter);
                if (sizeWriter.size() > config.getMaxBlockSize())
                    break;
                fee += transaction.getFee();
                include.add(transaction);
            }
            if (fee != 0L) {
                include.set(0, createCoinbase(height, minerAddress, config.getRewardForHeight(height) + fee));
            }
        } catch (IOException e) {
            throw new HyperLedgerException(e);
        }
        return include;
    }

    private static Transaction createCoinbase(int height, Address address, long subsidy) throws HyperLedgerException {
        WireFormat.ArrayWriter writer = new WireFormat.ArrayWriter();
        try {
            writer.writeUint32(height);
        } catch (IOException e) {
            // cannot happen
        }
        return Transaction.create().inputs(TransactionInput.create().source(new Outpoint(TID.INVALID, 0))
                .script(new Script(writer.toByteArray())).build())
                .outputs(ColoredTransactionOutput.create().payTo(address).value(subsidy).color(Color.BITCOIN).build()).build();
    }

    public void setMinerAddress(Address minerAddress) {
        this.minerAddress = minerAddress;
    }

    public Address getMinerAddress() {
        return minerAddress;
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            // nothing to do
        }
    }

    @Override
    public void blockStored(BlockStoredInfo content) {
        abortMiningNextBlock.set(true);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package br.com.crescer.entity;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "CIDADE")
@NamedQueries({
    @NamedQuery(name = "Cidade.findAll", query = "SELECT c FROM Cidade c")})

public class Cidade extends SerializableID<Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SQCIDADE")
    @SequenceGenerator(name = "SQCIDADE", sequenceName = "SQCIDADE", allocationSize = 1)
    @Basic(optional = false)
    @Column(name = "IDCIDADE")
    private Long id;

    @Basic(optional = false)
    @Column(name = "NOME")
    private String nome;

    @Basic(optional = false)
    @Column(name = "UF")
    private String uf;

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

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getUf() {
        return uf;
    }

    public void setUf(String uf) {
        this.uf = uf;
    }

    @Override
    public Long getId() {
        return id;
    }
}


text:
<?php

return [

    /**
     * Activity text strings.
     * Is used for all the text within activity logs & notifications.
     */

    // Pages
    'page_create'                 => 'created page',
    'page_create_notification'    => 'Page Successfully Created',
    'page_update'                 => 'updated page',
    'page_update_notification'    => 'Page Successfully Updated',
    'page_delete'                 => 'deleted page',
    'page_delete_notification'    => 'Page Successfully Deleted',
    'page_restore'                => 'restored page',
    'page_restore_notification'   => 'Page Successfully Restored',
    'page_move'                   => 'moved page',

    // Chapters
    'chapter_create'              => 'created chapter',
    'chapter_create_notification' => 'Chapter Successfully Created',
    'chapter_update'              => 'updated chapter',
    'chapter_update_notification' => 'Chapter Successfully Updated',
    'chapter_delete'              => 'deleted chapter',
    'chapter_delete_notification' => 'Chapter Successfully Deleted',
    'chapter_move'                => 'moved chapter',

    // Books
    'book_create'                 => 'created book',
    'book_create_notification'    => 'Book Successfully Created',
    'book_update'                 => 'updated book',
    'book_update_notification'    => 'Book Successfully Updated',
    'book_delete'                 => 'deleted book',
    'book_delete_notification'    => 'Book Successfully Deleted',
    'book_sort'                   => 'sorted book',
    'book_sort_notification'      => 'Book Successfully Re-sorted',

    // Other
    'commented_on'                => 'commented on',
];


text:
angular.module('contracker', ['ionic', 'contracker.services', 'contracker.controllers'])
.config(function($stateProvider, $urlRouterProvider) {
	$stateProvider
	.state('tab', {
		url: "/tab",
		abstract: true,
		templateUrl: 'templates/tabs.html'
	})
	.state('tab.lenses', {
		url: '/lenses',
		views: {
			'lenses-tab': {
				templateUrl: 'templates/lenses.html',
				controller: 'LensesIndexCtrl'
			}
		}
	})
	.state('tab.new', {
		url: '/new',
		views: {
			'new-tab': {
				templateUrl: 'templates/lense-detail.html',
				controller: 'LenseDetailCtrl'
			}
		}
	})
	.state('tab.edit', {
		url: '/lense/:id',
		views: {
			'lenses-tab': {
				templateUrl: 'templates/lense-detail.html',
				controller: 'LenseDetailCtrl'
			}
		}
	})
	.state('tab.settings', {
		url: '/settings',
		views: {
			'settings-tab' : {
				templateUrl: 'templates/settings.html',
				controller: 'SettingsCtrl'
			}
		}
	});

	//fallback route
	$urlRouterProvider.otherwise('tab/lenses');
});


text:
package com.amazonaws.services.simpleworkflow.model;

/**
 * Registration Status
 */
public enum RegistrationStatus {

    REGISTERED("REGISTERED"),
    DEPRECATED("DEPRECATED");

    private String value;

    private RegistrationStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *            real value
     * @return RegistrationStatus corresponding to the value
     */
    public static RegistrationStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");

        } else if ("REGISTERED".equals(value)) {
            return RegistrationStatus.REGISTERED;
        } else if ("DEPRECATED".equals(value)) {
            return RegistrationStatus.DEPRECATED;
        } else {
            throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
        }
    }
}


text:
package org.wso2.pc.integration.tests.publisher.processes;

import org.apache.wink.client.ClientResponse;
import org.apache.wink.common.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.pc.integration.test.utils.base.GenericRestClient;
import org.wso2.pc.integration.test.utils.base.PCIntegrationBaseTest;
import org.wso2.pc.integration.test.utils.base.PCIntegrationConstants;
import org.wso2.pc.integration.test.utils.base.TestUtils;

import javax.ws.rs.core.MediaType;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;

public class PublisherProcessLevelPermissionTestCase extends PCIntegrationBaseTest {

    GenericRestClient genericRestClient;
    String jSessionId;
    HashMap<String, String> queryMap;
    HashMap<String, String> headerMap;
    String resourcePath;
    private AutomationContext automationContextUser1;
    private String cookieHeader1;
    private String publisherUrl, APIUrl;
    private String requestBody, processId, Path;

    @DataProvider
    private static Object[][] userModeProvider() {
        return new TestUserMode[][]{
                new TestUserMode[]{TestUserMode.SUPER_TENANT_ADMIN}
        };
    }

    @BeforeClass(alwaysRun = true)
    public void createProcess() throws Exception {
        super.init();

        automationContextUser1=new AutomationContext("PC","designer","superTenant","user1");
        publisherUrl = automationContext.getContextUrls().getSecureServiceUrl().replace("services",
                PCIntegrationConstants.DESIGNER_APIS);
        cookieHeader1 = login(automationContextUser1);

        resourcePath = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator
                + "json" + File.separator + "process" + File.separator + "process.json";
        requestBody = readFile(resourcePath);
        queryMap.put("processInfo", URLEncoder.encode(requestBody, "UTF-8"));
        APIUrl = automationContext.getContextUrls().getSecureServiceUrl().replace("services",
                PCIntegrationConstants.DESIGNER_ASSETS + "/process/apis/create_process");
        ClientResponse response=genericRestClient.geneticRestRequestPost(APIUrl,
                MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, requestBody, queryMap,
                headerMap, cookieHeader1);
        log.info(response.getStatusCode() + " Process created successfully");
        JSONObject responseObject = new JSONObject(response.getEntity(String.class));
        processId = responseObject.get(PCIntegrationConstants.ID).toString();
        Path = "/_system/governance/processes/yasima/1.0";

    }

    /**
     * This test is to check whether the process creater has permission to assign different permission for different
     * users.
     *
     * @throws Exception
     */
    @Test(groups = {"org.wso2.pc"}, description = "Test authorize permission of the process creater")
    public void checkAuthorizePermission() throws Exception {

        headerMap = new HashMap<>();
        queryMap = new HashMap<>();
        queryMap.put("assetType", "process");
        queryMap.put("id", processId);

        ClientResponse response = genericRestClient.
                geneticRestRequestGet(publisherUrl + "/permissions", queryMap, headerMap, cookieHeader1);
        JSONObject responseObject = new JSONObject(response.getEntity(String.class));
        Assert.assertTrue(((response.getStatusCode() == HttpStatus.OK.getCode()) || (response.getStatusCode()
                        == HttpStatus.CREATED.getCode())),
                "Wrong status code ,Expected 200 OK or 201 OK ,Received " + response.getStatusCode());

        JSONObject data = (JSONObject) responseObject.get("data");
        JSONArray authorizedRoles = data.getJSONArray("authorizedRoles");
        Boolean status = false;
        for (int i = 0; i < authorizedRoles.length(); i++) {
            if (authorizedRoles.get(i).equals("role1")) {
                status = true;
                break;
            }
        }
        Boolean isAuthorizeAllowed = (Boolean) data.get("isAuthorizeAllowed");

        Assert.assertTrue(status && isAuthorizeAllowed, "Permission setting error");
    }

    /**
     * When a process is created only the process creater can edit and give permission for the process. This test case
     * is to test allowing write permission for another role.
     *
     * @throws IOException
     * @throws JSONException
     * @throws XPathExpressionException
     */
    @Test(groups = {"org.wso2.pc"}, description = "Adding write permission", dependsOnMethods =
            {"checkAuthorizePermission"})
    public void addPermission() throws IOException, JSONException, XPathExpressionException {

        headerMap = new HashMap<>();
        queryMap = new HashMap<>();
        requestBody = String.
                format(readFile(FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator
                                + "json" + File.separator + "process" + File.separator + "publisherPermissionAdd.json"),
                        processId, Path);
        ClientResponse response = genericRestClient.
                geneticRestRequestPost(publisherUrl + "/permissions", MediaType.APPLICATION_JSON,
                        MediaType.APPLICATION_JSON, requestBody, queryMap, headerMap, cookieHeader1);
        JSONObject responseObject = new JSONObject(response.getEntity(String.class));
        String responseStatus = responseObject.get("status").toString();
        Assert.assertTrue(((response.getStatusCode() == HttpStatus.OK.getCode()) ||
                        (response.getStatusCode() == HttpStatus.CREATED.getCode())),
                "Wrong status code ,Expected 200 OK or 201 OK ,Received " + response.getStatusCode());
        Assert.assertTrue(responseStatus.equals("true"), "Could not add permission to resource");
        Assert.assertTrue(isPermittedResource("role2", "writeAllow", cookieHeader1),
                "Could not add write permission");
    }

    @Test(groups = {"org.wso2.pc"}, description = "Removing write permission", dependsOnMethods = {"addPermission"})
    public void removePermission() throws IOException, JSONException, XPathExpressionException {

        headerMap = new HashMap<>();
        queryMap = new HashMap<>();
        queryMap.put("assetType", "process");
        queryMap.put("assetId", processId);
        queryMap.put("roleToRemove", "role2");
        queryMap.put("pathWithVersion", Path);

        ClientResponse response = genericRestClient.
                geneticRestRequestDelete(publisherUrl + "/permissions", MediaType.APPLICATION_JSON,
                        MediaType.APPLICATION_JSON, queryMap, headerMap, cookieHeader1);
        JSONObject responseObject = new JSONObject(response.getEntity(String.class));
        String responseStatus = responseObject.get("status").toString();
        Assert.assertTrue(((response.getStatusCode() == HttpStatus.OK.getCode()) ||
                        (response.getStatusCode() == HttpStatus.CREATED.getCode())),
                "Wrong status code ,Expected 200 OK or 201 OK ,Received " + response.getStatusCode());
        Assert.assertTrue(responseStatus.equals("true"), "Could not remove permission to resource");
        Assert.assertTrue(isPermittedResource("role2", "writeDeny", cookieHeader1),
                "Could not remove permission of resource");

    }

    /**
     * The requirement is any user can view the any process. For that internal/everyone should have read permission.
     *
     * @throws Exception
     */

    @Test(groups = {"org.wso2.pc"}, description = "Test Read permission")
    public void viewProcess() throws Exception {

        Assert.assertTrue(isPermittedResource("INTERNAL/everyone", "readAllow", cookieHeader1), "Read Permission " +
                "error");
    }

    @Test(groups = {"org.wso2.pc"}, description = "Test edit process", dependsOnMethods = {"addPermission"})
    public void EditProcess() throws Exception {

        headerMap = new HashMap<>();
        queryMap = new HashMap<>();
        AutomationContext automationContextUser2 = new AutomationContext("PC", "designer", "superTenant", "user2");
        String cookieHeader2 = login(automationContextUser2);
        APIUrl = automationContext.getContextUrls().getSecureServiceUrl().replace("services",
                PCIntegrationConstants.DESIGNER_ASSETS + "/process/apis/update_description");

        requestBody = String.
                format(readFile(FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator
                                + "json" + File.separator + "process" + File.separator + "edit-process.json"),
                        processId, Path);
        queryMap.put("descriptionDetails", URLEncoder.encode(requestBody, "UTF-8"));
        ClientResponse response = genericRestClient.geneticRestRequestPost(APIUrl,
                MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON,
                requestBody, queryMap, headerMap, cookieHeader2);
        response.getStatusCode();
        JSONObject responseObject = new JSONObject(response.getEntity(String.class));

        Assert.assertTrue(((response.getStatusCode() == HttpStatus.OK.getCode())),
                "Wrong status code ,Expected 200 OK or 201 OK ,Received " + response.getStatusCode());
        Assert.assertFalse(responseObject.get("error").equals("false"), "Could not update resource");

    }

    @Test(groups = {"org.wso2.pc"}, description = "Test edit process without write permission",
            dependsOnMethods = {"removePermission"})
    public void checkEditProcessWithoutReadPermission() throws Exception {

        boolean status = isPermittedResource("role2", "writeDeny", cookieHeader1);
        Assert.assertTrue(status, "Write permission error");

    }

    @AfterClass(alwaysRun = true)
    public void cleanUp(){
        automationContextUser1=null;
        //delete process

    }

    public String login(AutomationContext automationCxt) throws Exception {

        genericRestClient = new GenericRestClient();
        headerMap = new HashMap<>();
        queryMap = new HashMap<>();
        JSONObject objSessionPublisher =
                new JSONObject(TestUtils.authenticate(publisherUrl, genericRestClient,
                        automationCxt.getContextTenant().getContextUser().getUserName(),
                        automationCxt.getContextTenant().getContextUser().getPassword(), queryMap,
                        headerMap).getEntity(String.class));
        jSessionId = objSessionPublisher.getJSONObject("data").getString("sessionId");

        return "JSESSIONID=" + jSessionId;
    }

    private Boolean isPermittedResource(String role, String permissionType, String cookieHeader)
            throws JSONException, IOException {

        queryMap.put("assetType", "process");
        queryMap.put("id", processId);

        ClientResponse response = genericRestClient.
                geneticRestRequestGet(publisherUrl + "/permissions", queryMap, headerMap, cookieHeader);
        JSONObject responseObject = new JSONObject(response.getEntity(String.class));
        Assert.assertTrue(((response.getStatusCode() == HttpStatus.OK.getCode()) || (response.getStatusCode()
                        == HttpStatus.CREATED.getCode())),
                "Wrong status code ,Expected 200 OK or 201 OK ,Received " + response.getStatusCode());

        JSONObject data = (JSONObject) responseObject.get("data");
        JSONArray permissionArray = data.getJSONArray("list");
        Boolean status = false;
        for (int i = 0; i < permissionArray.length(); i++) {
            JSONObject roleObject = permissionArray.getJSONObject(i);
            if (roleObject.get("userName").equals(role) && roleObject.getBoolean(permissionType)) {
                status = true;
                break;
            }
        }

        return status;
    }
}


text:
class CreateGuessesTable < ActiveRecord::Migration
  def change
    create_table :guesses do |t|
      t.references :round
      t.references :card
      t.boolean :correct
      t.string :answer

      t.timestamps null: false
    end
  end
end


text:
```json
{
  "general": {
    "api": {
      "port": 3456,
      "users": [
        {
          "user": "runnerty",
          "password": "password_runnerty"
        },
        {
          "user": "usr_test",
          "password": "pass_test"
        }
      ],
      "secret": "RUNNERTY_SECRET_SAMPLE",
      "limite_req": "20mb"
    }
  }
}
```

## Autenticación

Login para obtener token de acceso

### POST [/auth/]

- Body parameters
  - user (string)
    Usuario
  - password (string)
    Contraseña

* Sample (body)

```json
{
  "user": "runnerty",
  "password": "password_runnerty"
}
```

Es importante tener en cuenta que en todas las llamadas a la API (excepto /auth/) deben contener las cabeceras:

`Content-Type: application/json`
`Authorization: Bearer [TOKEN_RESULTANTE_DE_AUTH]`

## Consultar el estado del servicio

Devuelve un http 200 si runnerty está ejecutándose

### GET [/health/]

- Sample (url)
  http://sample_host.com/api/health

## Consultar cadenas

Consultar cadenas cargadas

### GET [/chains/]

## Consultar cadena

Consultar una cadena

### GET [/chain/:chainId:uniqueId]]

- URL parameters

  - chainId (ID de la cadena)
  - uniqueId (uId de la cadena)

- Sample (url)
  http://sample_host.com/api/chain/CHAIN_SAMPLE

## Forzar ejecución de una cadena

Se ejecutará la cadena indicada siempre que no esté corrienda ya.

### POST [/chain/forceStart/:chainId]

- URL parameters

  - chainId (ID de la cadena)

- Sample (url)
  http://sample_host.com/api/chain/forceStart/CHAIN_SAMPLE

- Body parameters

  - customValues (object)
    - GLOBAL_VALUE_KEY:VALUE_KEY (Variable global y valor personalizado)

- Sample (body)

```json
{
  "customValues": {
    "YYYY": "1986",
    "MY_CONF_VALUE": "NEW_VALUE"
  }
}
```

## Consultar procesos de una cadena

Consultar procesos de una cadena

### GET [/processes/:chainId]

- URL parameters

  - chainId (ID de la cadena)

- Sample (url)
  http://sample_host.com/api/processes/CHAIN_SAMPLE

## Consultar proceso de una cadena

Consultar proceso de una cadena

### GET [/process/:chainId/:processId]

- URL parameters

  - chainId (ID de la cadena)
  - processId (ID del proceso)

- Sample (url)
  http://sample_host.com/api/process/CHAIN_SAMPLE/PROCESS_ONE

## Matar proceso de una cadena

Matar un proceso de una cadena

### POST [/process/kill]

- Sample (url)
  http://sample_host.com/api/process/kill

- Body parameters
  - chainId (ID de la cadena)
  - uniqueId (uId de la cadena)
  - processId (ID del proceso)
- Sample (body)

```json
{
  "chainId": "CHAIN_ONE",
  "processId": "PROCESS_ONE"
}
```

## Configuración de CORS

Parámetros de configuración de CORS de la API:

### Opciones

Consulte las opciones de configuración en la documentación del módulo [expressjs/cors](https://github.com/expressjs/cors/blob/master/README.md#configuration-options)

Ejemplo:

```json
{
  "general": {
    "api": {
      "port": 3456,
      "users": [
        {
          "user": "runnerty",
          "password": "password_runnerty"
        },
        {
          "user": "usr_test",
          "password": "pass_test"
        }
      ],
      "secret": "RUNNERTY_SECRET_SAMPLE",
      "limite_req": "20mb",
      "cors": {
        "origin": "*",
        "methods": "GET,POST",
        "allowedHeaders": "X-Requested-With,content-type",
        "credentials": false,
        "preflightContinue": false,
        "optionsSuccessStatus": 204
      }
    }
  }
}
```


text:
__resources__["/componentAdder.js"] = {meta: {mimetype: "application/javascript"}, data: function(exports, require, module, __filename, __dirname) {

 var MouseButtonEventComponent = require('component').MouseButtonEventComponent;
 var HoverEventComponent = require('component').HoverEventComponent;
 var clientManager = require('clientManager');

	/**
	 * add component to entity, such as mouseButtonEventComponent
	 */
	var ComponentAdder = function(opts){
		var area = opts.area;
		this.addComponent = function(){
			addClickComponent(area);
		};

		this.addComponentTo = function(entity) {
			addComponentToEntity(area, entity);
		};
	};

	/**
	 * add clickComponet to map
	 */
	var addClickComponent = function(area) {
		var clickComponentPlayer = new MouseButtonEventComponent({
			pipe: area.gLevel.sysPipe(),
			decider: area.scene.queryDecider('mouseButtonDecider'),
			callback: move.bind(null, area)
		});

		area.map.node.addComponent('mouseButtonEventComponent', clickComponentPlayer);
	};

	var move = function(area, event) {
		var player = area.getCurPlayer();
		var sprite = player.getSprite();
		if (event.type === 'mousePressed'){
			var endX = Math.floor(event.mouseX - sprite.getMapPosition().x);
			var endY = Math.floor(event.mouseY - sprite.getMapPosition().y);
			var startX = Math.floor(sprite.getPosition().x);
			var startY = Math.floor(sprite.getPosition().y);
			var moveMessage = {
				startX: startX,
				startY: startY,
				endX: endX,
				endY: endY,
				playerId: player.id,
				areaId: area.id,
				speed: sprite.entity.walkSpeed
			};
			clientManager.move(moveMessage);
		}
	};

	/**
	 * add mouseClick component to entity
	 */
	var addComponentToEntity = function(area, entity) {
		//add mouseButtonEvent to entities
		var clickComponentEntity = new MouseButtonEventComponent({
			pipe: area.gLevel.sysPipe(),
			decider: area.scene.queryDecider('mouseButtonDecider'),
			callback: launchAi
		});
		var node = entity.getSprite().curNode;
		node.addComponent('mouseButtonEventComponent', clickComponentEntity);
		//add HoverEventComponent to entities
		var hoverEventComponent = new HoverEventComponent({
			pipe: area.gLevel.sysPipe(),
			decider: area.scene.queryDecider('hoverDecider'),
			callback: hover
		});
		node.addComponent('hoverEventComponent', hoverEventComponent);
	};

	/**
	 * Mouse hover handlerFunction
	 */
	var hover = function(event) {
		var type = event.type;
		var c = $('canvas');
		if (type == 'mouseOver') {
			c.css('cursor', 'pointer');
		} else {
			c.css('cursor', 'default');
		}
	};

	/**
	 * Mouse click handlerFunction
	 */
	var launchAi = function (event, node) {
		var id = node.id;
		if (event.type === 'mouseClicked') {
			clientManager.launchAi({id: id});
		}
	};

	module.exports = ComponentAdder;
}};


text:
        <md-toolbar class="md-whiteframe-z1 site-content-toolbar">

          <md-button class="md-icon-button md-button md-ink-ripple hide-gt-sm" type="button" ng-transclude="" ng-click="toggleLeft()" hide-gt-sm aria-label="Toggle Menu">
          <md-icon md-svg-src="../img/icons/menu.svg"></md-icon>
          </md-button>

              Angular Application by Damir Durmo

        </md-toolbar>
      <md-content class="md-padding">

Project Description:

This is an application (Online store) build using Angular, Angular Material, Sass, Node, Gulp, Bower

      </md-content>

  <md-toolbar>
Search Cars for sale
</md-toolbar>

    <md-input-container flex-gt-sm>
      What are you looking for?
      <input class="form-group label-floating"ng-model="query">
    </md-input-container>
    <md-input-container flex-gt-sm>
    Sort by:
    <md-select ng-model="orderProp">
      <md-option value="name">Alphabetical</md-option>
      <md-option value="year">Newest</md-option>
    </md-select>
    </md-input-container flex-gt-sm>
    <md-input-container>
      Search By Year
      <input class="form-group label-floating"ng-model="year">
    </md-input-container>

    <md-card  flex-gt-sm="45" flex-xs="80" ng-repeat="product in products | filter:query | orderBy:orderProp | filter:year">
      <md-card-title>
        <md-card-title-text>
        {{product.year}} {{product.name}}
          {{product.snippet}}

        </md-card-title-text>
        <md-card-title-media>

        </md-card-title- media>
      </md-card-title>
      <md-card-actions layout="row" flex layout-align="center center">
        {{product.price | currency}}
      </md-card-actions>
  </md-card>


text:
package my.designpatterns.proxy.remote.gumball;

public class NoQuarterState implements State{
	private transient GumballMachine gumballMachine;

	public NoQuarterState(GumballMachine gumballMachine) {
		super();
		this.gumballMachine = gumballMachine;
	}

	public void insertQuarter() {
		// TODO Auto-generated method stub
		System.out.println("동전을 넣으셨습니다.");
		gumballMachine.setState(gumballMachine.getHasQuarterState());
	}

	public void ejectQuarter() {
		// TODO Auto-generated method stub
		System.out.println("동전을 넣어주세요.");
	}

	public void turnCrank() {
		// TODO Auto-generated method stub
		System.out.println("동전을 넣어주세요.");
	}

	public void dispense() {
		// TODO Auto-generated method stub
		System.out.println("동전을 넣어주세요.");
	}

}


text:
	clear: left;
	font-weight: bold;
	font-size: 20px;
	text-align: center;
	float: left;
}
#achievements-list div.item-desc {
	width: auto;
}
#achievements-list div.meta {
	margin-top: 0;
}
#achievements-list img.avatar-thumbnail {
	width: 50px;
}
#achievements-list li.inactive, #achievements-list li.active-but-hidden {
	background-color: #F4F4F4;
}
#achievements-list li div.action p.quickadmin {
	display: none;
}
#achievements-list li:hover div.action p.quickadmin {
	display: block;
}


text:
require 'spec_helper'

RSpec.describe Aspector::Logging do
  subject { described_class }
  let(:context) { double }

  describe '.build' do
    before do
      subject.instance_variable_set('@logger', logger)
    end

    after do
      subject.instance_variable_set('@logger', nil)
    end

    let(:logger) { nil }
    let(:klass_name) { 'NonExisting' }

    context 'and given logger class doesnt exist' do
      before do
        expect(ENV)
          .to receive(:[])
          .and_return(klass_name)
          .at_least(:once)

        expect($stderr)
          .to receive(:puts)
          .with("#{klass_name} is not a valid constant name!")
      end

      it 'should use Aspector::Logger' do
        expect(subject.build(context)).to be_instance_of(Aspector::Logger)
      end
    end

    context 'and given logger class exists' do
      let(:dummy_logger) { 'DummyLogger' }

      before do
        expect(ENV)
          .to receive(:[])
          .and_return(dummy_logger)
          .at_least(:once)

        expect(Object)
          .to receive(:const_get)
          .with(dummy_logger)
          .and_return(Aspector::Logger)
      end

      it 'should use it' do
        expect(subject.build(context)).to be_instance_of(Aspector::Logger)
      end
    end
  end

  describe '.deconstantize' do
    context 'and given logger class doesnt exist' do
      let(:klass_name) { 'NonExisting' }

      before do
        expect($stderr)
          .to receive(:puts)
          .with("#{klass_name} is not a valid constant name!")
      end

      it 'should return internal logger class' do
        expect(subject.send(:deconstantize, klass_name)).to eq Aspector::Logger
      end
    end

    context 'and given logger class exists' do
      let(:klass_name) { 'Aspector::Logger' }

      before do
        expect($stderr)
          .not_to receive(:puts)
      end

      it 'should return it deconstantized' do
        expect(subject.send(:deconstantize, klass_name)).to eq Aspector::Logger
      end
    end
  end
end


text:
package com.o2d.pkayjava.runtime.data;

import com.o2d.pkayjava.runtime.data.*;
import com.o2d.pkayjava.runtime.data.MainItemVO;

public class TextBoxVO extends MainItemVO {

	public String defaultText = "";
	public float width = 0;
	public float height = 0;
	public String	style	=  "";

	public TextBoxVO() {
		super();
	}

	public TextBoxVO(TextBoxVO vo) {
		super(vo);
		defaultText = new String(vo.defaultText);
		width 		= vo.width;
		height 		= vo.height;
		style 		= new String(vo.style);
	}
}


text:
<html>
	<head>
		<title>Car Sales App</title>
        <link rel= "stylesheet" href="css/styles.css">
	</head>
	<body>


text:
.class public final Llibcore/icu/NativeCollation;
.super Ljava/lang/Object;
.source "NativeCollation.java"

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 21
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 22
    return-void
.end method

.method public static native closeCollator(J)V
.end method

.method public static native closeElements(J)V
.end method

.method public static native compare(JLjava/lang/String;Ljava/lang/String;)I
.end method

.method public static native getAttribute(JI)I
.end method

.method public static native getCollationElementIterator(JLjava/lang/String;)J
.end method

.method public static native getMaxExpansion(JI)I
.end method

.method public static native getOffset(J)I
.end method

.method public static native getRules(J)Ljava/lang/String;
.end method

.method public static native getSortKey(JLjava/lang/String;)[B
.end method

.method public static native next(J)I
.end method

.method private static native openCollator(Ljava/lang/String;)J
.end method

.method public static openCollator(Ljava/util/Locale;)J
    .locals 2
    .param p0, "locale"    # Ljava/util/Locale;

    .prologue
    .line 32
    invoke-virtual {p0}, Ljava/util/Locale;->toLanguageTag()Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Llibcore/icu/NativeCollation;->openCollator(Ljava/lang/String;)J

    move-result-wide v0

    return-wide v0
.end method

.method public static native openCollatorFromRules(Ljava/lang/String;II)J
.end method

.method public static native previous(J)I
.end method

.method public static native reset(J)V
.end method

.method public static native safeClone(J)J
.end method

.method public static native setAttribute(JII)V
.end method

.method public static native setOffset(JI)V
.end method

.method public static native setText(JLjava/lang/String;)V
.end method


text:
/**
 * Module dependencies.
 */

var _ = require('lodash')
	, express = require('express');

module.exports = function(sails) {

	var defaultHandlers = require('./bindDefaultHandlers')(sails);

	/**
	 * Expose new instance of `Router`
	 *
	 * @api private
	 */

	return new Router();

	/**
	 * Initialize a new `Router`
	 *
	 * @param {Object} options
	 * @api private
	 */

	function Router (options) {

		/**
		 * _slave
		 *
		 * This internal "slave" instance of an Express app object
		 * is used only for routing. (i.e. it will not be used for
		 * listening to actual HTTP requests; instead, one or more
		 * delegate servers can be attached- see the `http` or
		 * `sockets` hooks for examples of attaching a server to
		 * Sails)
		 *
		 * NOTE: Requires calling `load()` before use in order to
		 * provide access to the proper NODE_ENV, since Express
		 * uses that to determine its environment (development vs.
		 * production.)
		 */

		Router.prototype._slave;

		/**
		 * `sails.router.load()`
		 *
		 * Expose the router, create the Express slave router,
		 * then call flush(), which will bind configured routes
		 * and emit the appropriate events.
		 *
		 * @api public
		 */

		Router.prototype.load = function(cb) {

			sails.log.verbose('Loading router...');

			// Required for dynamic NODE_ENV setting via command line args
			this._slave = express();

			// Maintain a reference to the static route config
			this.explicitRoutes = sails.config.routes;

			// Save reference to sails logger
			this.log = sails.log;

			// Expose router on `sails` object
			sails.router = this;

			// Wipe any existing routes and bind them anew
			this.flush();

			// Listen for requests
			sails.on('router:request', this.route);

			// Listen for unhandled errors and unmatched routes
			sails.on('router:request:500', defaultHandlers[500]);
			sails.on('router:request:404', defaultHandlers[404]);

			cb();
		};

		/**
		 * `sails.router.route()`
		 *
		 * Set up a `request` listener which can be used to trigger routes
		 *
		 * NOTE: this should only be used if the request handler does not have its own router.
		 * (this approach also dramatically simplifies unit testing!)
		 *
		 * The optimal behavior for Express, for instance, is to listen to `router:bind`
		 * and use the built-in router at lift-time, whereas Socket.io needs to use the
		 * `router:request` event to simulate a connect-style router since it
		 * can't bind dynamic routes ahead of time.
		 *
		 * By default, params and IO methods like res.send() are noops that should be overridden.
		 *
		 * Keep in mind that, if `route` is not used, the implementing server is responsible
		 * for routing to Sails' default `next(foo)` handler.
		 *
		 * @param {Object} req
		 * @param {Object} res
		 * @param {Function} next [optional callback- used to populate default res.send() behavior]
		 * @api private
		 */

		Router.prototype.route = function(req, res, next) {

			// Bundle raw callback function
			res._cb = next || function noRouteCbSpecified (err) { if (err) return sails.log.error(err); };

			// Track request start time
			req._startTime = new Date();

			// Make sure request and response objects have reasonable defaults
			// (will use the supplied definitions if possible)
			req = reasonableDefaultRequest(req);
			res = reasonableDefaultResponse(res);

			// Use our slave router to route the request
			this._slave.router(req, res, function handleUnmatchedNext(err) {

				//
				// In the event of an unmatched `next()`, `next('foo')`,
				// or `next('foo', errorCode)`...
				//

				// Use the default server error handler
				if (err) {
					sails.emit('router:request:500', err, req, res);
					return;
				}

				// Or the default not found handler
				sails.emit('router:request:404', req, res);
				return;
			});

		};

		/**
		 * `sails.router.bind()`
		 *
		 * Bind new route(s)
		 *
		 * @param {String|RegExp} path
		 * @param {String|Object|Array|Function} bindTo
		 * @param {String} verb
		 * @api private
		 */

		Router.prototype.bind = require('./bind')(sails);

		/**
		 * `sails.router.unbind()`
		 *
		 * Unbind existing route
		 *
		 * @param {Object} route
		 * @api private
		 */

		Router.prototype.unbind = function(route) {

			// Inform attached servers that route should be unbound
			sails.emit('router:unbind', route);

			// Remove route in internal router
			var newRoutes = [];
			_.each(this._slave.routes[route.method], function(expressRoute) {
				if (expressRoute.path != route.path) {
					newRoutes.push(expressRoute);
				}
			});
			this._slave.routes[route.method] = newRoutes;

		};

		/**
		 * `sails.router.reset()`
		 *
		 * Unbind all routes currently attached to the router
		 *
		 * @api private
		 */

		Router.prototype.reset = function () {

			// Unbind everything
			_.each(this._slave.routes, function(routes, httpMethod) {

				// Unbind each route for the specified HTTP verb
				var routesToUnbind = this._slave.routes[httpMethod] || [];
				_.each(routesToUnbind, this.unbind, this);

			}, this);

			// Emit reset event to allow attached servers to
			// unbind all of their routes as well
			sails.emit('router:reset');

		};

		/**
		 * `sails.router.flush()`
		 *
		 * Unbind all current routes, then re-bind everything, re-emitting the routing
		 * lifecycle events (e.g. `router:before` and `router:after`)
		 *
		 * @param {Object} routes - (optional)
		 *  If specified, replaces `this.explicitRoutes` before flushing.
		 *
		 * @api private
		 */

		Router.prototype.flush = function( routes ) {

			// Wipe routes
			this.reset();

			// Fired before static routes are bound
			sails.emit('router:before');

			// If specified, replace `this.explicitRoutes`
			if (routes) {
				this.explicitRoutes = routes;
			}

			// Use specified path to bind static routes
			_.each(this.explicitRoutes, function(target, path) {
				this.bind(path, target);
			}, this);

			// Fired after static routes are bound
			sails.emit('router:after');
		};

		// Bind the context of all instance methods
		_.bindAll(this);

	}

	//
	// TODO:
	// replace w/ req.js and res.js:
	//

	/**
	 * Ensure that request object has a minimum set of reasonable defaults.
	 * Used primarily as a test fixture.
	 *
	 * @api private
	 */

	function reasonableDefaultRequest(req) {
		return _.defaults(req || {}, {
			params: {},
			param: function(paramName) {
				return req.params[paramName];
			},
			wantsJSON: true,
			method: 'get'
		});
	}

	/**
	 * Ensure that response object has a minimum set of reasonable defaults
	 * Used primarily as a test fixture.
	 *
	 * @api private
	 */

	function reasonableDefaultResponse(res) {
		return _.defaults(res || {}, {
			send: function(body, status) {
				res._cb(body, status);
			},
			json: function(body, status) {

				// Tolerate bad JSON
				var json = sails.util.stringify(body);
				if ( !json ) {
					var failedStringify = new Error(
						'Failed to stringify specified JSON response body :: ' + body
					);
					return res.send(failedStringify.stack, 500);
				}

				return res.send(json,status);
			}
		});
	}

};


text:
require 'rubygems/test_case'
require 'rubygems/commands/which_command'

class TestGemCommandsWhichCommand < Gem::TestCase

  def setup
    super
    Gem::Specification.reset
    @cmd = Gem::Commands::WhichCommand.new
  end

  def test_execute
    util_foo_bar

    @cmd.handle_options %w[foo_bar]

    use_ui @ui do
      @cmd.execute
    end

    assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
    assert_equal '', @ui.error
  end

  def test_execute_directory
    @cmd.handle_options %w[directory]

    use_ui @ui do
      assert_raises Gem::MockGemUi::TermError do
        @cmd.execute
      end
    end

    assert_equal '', @ui.output
    assert_match %r%Can.t find ruby library file or shared library directory\n%,
                 @ui.error
  end

  def test_execute_one_missing
    # TODO: this test fails in isolation

    util_foo_bar

    @cmd.handle_options %w[foo_bar missinglib]

    use_ui @ui do
      assert_raises Gem::MockGemUi::TermError do
        @cmd.execute
      end
    end

    assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
    assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
                 @ui.error
  end

  def test_execute_missing
    @cmd.handle_options %w[missinglib]

    use_ui @ui do
      assert_raises Gem::MockGemUi::TermError do
        @cmd.execute
      end
    end

    assert_equal '', @ui.output
    assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
                 @ui.error
  end

  def util_foo_bar
    files = %w[lib/foo_bar.rb lib/directory/baz.rb Rakefile]
    @foo_bar = util_spec 'foo_bar' do |gem|
      gem.files = files
    end
    install_specs @foo_bar

    files.each do |file|
      filename = File.join(@foo_bar.full_gem_path, file)
      FileUtils.mkdir_p File.dirname filename
      FileUtils.touch filename
    end
  end

end


text:
#ifndef __INET_ETHERENCAP_H
#define __INET_ETHERENCAP_H

#include "inet/common/INETDefs.h"

#include "inet/linklayer/ethernet/Ethernet.h"

namespace inet {

// Forward declarations:
class EtherFrame;

/**
 * Performs Ethernet II encapsulation/decapsulation. More info in the NED file.
 */
class INET_API EtherEncap : public cSimpleModule
{
  protected:
    int seqNum;

    // statistics
    long totalFromHigherLayer;    // total number of packets received from higher layer
    long totalFromMAC;    // total number of frames received from MAC
    long totalPauseSent;    // total number of PAUSE frames sent
    int interfaceId = -1;
    static simsignal_t encapPkSignal;
    static simsignal_t decapPkSignal;
    static simsignal_t pauseSentSignal;
    bool useSNAP;    // true: generate EtherFrameWithSNAP, false: generate EthernetIIFrame

  protected:
    virtual int numInitStages() const override { return NUM_INIT_STAGES; }
    virtual void initialize(int stage) override;
    virtual void handleMessage(cMessage *msg) override;

    virtual void processPacketFromHigherLayer(cPacket *msg);
    virtual void processFrameFromMAC(EtherFrame *msg);
    virtual void handleSendPause(cMessage *msg);

    virtual void refreshDisplay() const override;
};

} // namespace inet

#endif // ifndef __INET_ETHERENCAP_H