repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
pypa/warehouse
warehouse/utils/db/windowed_query.py
2050
# 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. # Taken from "Theatrum Chemicum" at # https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/WindowedRangeQuery from sqlalchemy import and_, func, text def column_windows(session, column, windowsize): """ Return a series of WHERE clauses against a given column that break it into windows. Result is an iterable of tuples, consisting of ((start, end), whereclause), where (start, end) are the ids. Requires a database that supports window functions, i.e. Postgresql, SQL Server, Oracle. Enhance this yourself ! Add a "where" argument so that windows of just a subset of rows can be computed. """ def int_for_range(start_id, end_id): if end_id: return and_(column >= start_id, column < end_id) else: return column >= start_id q = session.query( column, func.row_number().over(order_by=column).label("rownum") ).from_self(column) if windowsize > 1: q = q.filter(text("rownum %% %d=1" % windowsize)) intervals = [row[0] for row in q] while intervals: start = intervals.pop(0) if intervals: end = intervals[0] else: end = None yield int_for_range(start, end) def windowed_query(q, column, windowsize): """ Break a Query into windows on a given column. """ for whereclause in column_windows(q.session, column, windowsize): for row in q.filter(whereclause).order_by(column): yield row
apache-2.0
tomsnail/snail-dev-console
src/main/java/com/thinkgem/jeesite/modules/act/service/cmd/CreateAndTakeTransitionCmd.java
1755
package com.thinkgem.jeesite.modules.act.service.cmd; import java.util.Map; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.Command; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.TaskEntity; import org.activiti.engine.impl.pvm.process.ActivityImpl; import org.activiti.engine.impl.pvm.runtime.AtomicOperation; public class CreateAndTakeTransitionCmd implements Command<java.lang.Void> { private TaskEntity currentTaskEntity; private ActivityImpl activity; protected Map<String, Object> variables; public CreateAndTakeTransitionCmd(TaskEntity currentTaskEntity, ActivityImpl activity, Map<String, Object> variables) { this.currentTaskEntity = currentTaskEntity; this.activity = activity; this.variables = variables; } @Override public Void execute(CommandContext commandContext) { if (currentTaskEntity != null) { ExecutionEntity execution = commandContext.getExecutionEntityManager().findExecutionById(currentTaskEntity.getExecutionId()); execution.setActivity(activity); execution.performOperation(AtomicOperation.TRANSITION_CREATE_SCOPE); if (variables != null) { if (currentTaskEntity.getExecutionId() != null) { currentTaskEntity.setExecutionVariables(variables); } else { currentTaskEntity.setVariables(variables); } } //删除当前的任务,不能删除当前正在执行的任务,所以要先清除掉关联 Context.getCommandContext().getTaskEntityManager().deleteTask(currentTaskEntity, TaskEntity.DELETE_REASON_DELETED, false); } return null; } }
apache-2.0
jmapper-framework/jmapper-test
JMapper Test/src/test/java/com/googlecode/jmapper/integrationtest/others/github/bean/EnumDest.java
218
package com.googlecode.jmapper.integrationtest.others.github.bean; public class EnumDest { private Test test; public Test getTest() { return test; } public void setTest(Test test) { this.test = test; } }
apache-2.0
rwth-acis/REST-OCD-Services
rest_ocd_services/src/test/java/i5/las2peer/services/ocd/cooperation/data/table/TableTest.java
648
package i5.las2peer.services.ocd.cooperation.data.table; import org.junit.Test; import i5.las2peer.services.ocd.cooperation.data.table.Table; import i5.las2peer.services.ocd.cooperation.data.table.TableRow; public class TableTest { @Test public void printTableTest() { Table table = new Table(); TableRow row1 = new TableRow(); TableRow row2 = new TableRow(); TableRow row3 = new TableRow(); row1.add("aaa").add("1234").add("yxcv").add("vvv"); row2.add("bbb").add("125").add("qwer").add("www"); row3.add("ccc").add("654").add("asdf").add("zzz"); table.add(row1); table.add(row2); table.add(row3); } }
apache-2.0
israelz11/municipio
WebContent/include/js/toolSam.js
78465
var centro = "text-align:center"; var derecha = "text-align:right"; var izquierda = "text-align:left"; var row_color = ""; function mostrarOpcionPDF(cve_op){//Muestra la opcion de reportes desde el listado de ordenes de pago... swal({ title: 'Opciones de Reporte OP #'+cve_op, type: 'question', width: 350, confirmButtonText: 'Cerrar', html: '<table class="table table-striped table-hover" border="0" align="center" cellpadding="1" cellspacing="2" width="405" >'+ ' <tr> '+ ' <td width="33" height="27" align="center" style="cursor:pointer" onclick="getReporteOP('+cve_op+')"> '+ ' <img src="../../imagenes/pdf.gif"/></td>' + ' <td width="362" height="27" align="left" style="cursor:pointer" onclick="getReporteOP('+cve_op+')">&nbsp;Reporte Normal</td> '+ ' </tr> '+ ' <tr> '+ ' <td height="27" align="center" style="cursor:pointer" onclick="getAnexosListaOP('+cve_op+')"><img src="../../imagenes/report.png" /></td> '+ ' <td height="27" align="left" style="cursor:pointer" onclick="getAnexosListaOP('+cve_op+')">&nbsp;Listar Anexos</td> '+ ' </tr> '+ '</table>', }); $('#swal2-title').css({'font-size':'20px'}); } function muestraVales(){ var clv_benefi = $('#xClaveBen').attr('value'); var tipo_gto = $('#tipoGasto').val(); var tipo_doc = $('#cbotipo').val(); var idDependencia = $('#cbodependencia').val(); if(typeof(clv_benefi)=='undefined') clv_benefi =0; if(typeof(tipo_gto)=='undefined') tipo_gto =0; if(typeof(tipo_doc)=='undefined') tipo_doc =0; if(typeof(idDependencia)=='undefined') idDependencia =0; if($('#txtvale').attr('value')=='') $('#CVE_VALE').attr('value', 0); swal({ title: 'Listado de Vales disponibles', html: '<iframe width="750" height="350" name="ventanaVales" id="ventanaVales" frameborder="0" src="../../sam/consultas/muestra_vales.action?idVale='+$('#CVE_VALE').attr('value')+'&idDependencia='+idDependencia+'&tipo_gto='+tipo_gto+'&clv_benefi='+clv_benefi+'&tipo_doc='+tipo_doc+'"></iframe>', width: 800, padding: 10, animation: false }) //jWindow(,'', '','Cerrar',1); } function muestraContratos(){ var idDependencia = $('#unidad2').attr('value'); var num_contrato = $('#txtnumcontrato').attr('value'); var tipo_gto = $('#tipoGasto').val(); if(typeof tipo_gto=='undefined') tipo_gto =""; if(typeof idDependencia=='undefined') idDependencia = null; //jWindow(','', '','Cerrar',1); swal({ title: 'Listado de Contratos Disponibles', html: '<iframe width="800" height="400" name="CONTRATO" id="CONTRATO" frameborder="0" src="../../sam/consultas/muestra_contratos.action?idDependencia='+idDependencia+'&tipo_gto='+tipo_gto+'&num_contrato='+num_contrato+'"></iframe>', width: 800, padding: 10, animation: false }) } function removerVale(){ $('#CVE_VALE').attr('value', '0'); $('#txtvale').attr('value', ''); $('#img_quitar_vale').attr('src', '../../imagenes/cross2.png'); } /*funcion para remover los elementos de un contrato*/ function removerContrato(){ $('#CVE_CONTRATO').attr('value', '0'); $('#txtnumcontrato').attr('value', ''); $('#CCLV_PARBIT').attr('value', ''); $('#CPROYECTO').attr('value', ''); $('#CCLV_PARTID').attr('value', ''); $('#CCLV_BENEFI').attr('value', ''); //$('#img_quitar_contrato').attr('src', '../../imagenes/cross2.png'); contrato = false; } /*********************************** funcion para el cambio de grupo de firmas 29/08/2017 ************************************************************/ function cambiarGrupoFirmas(cve_doc, modulo){ swal({ title: 'Cambiar grupo de firmas', text: 'Seleccione el nuevo grupo de firma', html: '<iframe width="800" height="350" name="grupoFirmas" id="grupoFirmas" frameborder="0" src="../../sam/utilerias/cambiarFirmas.action?modulo='+modulo+'&cve_doc='+cve_doc+'"></iframe>', width: 800, padding: 10, animation: false }) } /*funcion para editar los documentos*/ function abrirDocumento(){ swal({ title: 'El modulo no se encuentra desarrollado y no esta disponible por el momento!', text: 'Por modificaciones de lineamientos de la CONAC.', type: 'info', showConfirmButton: false, timer: 3000 }).then( function () {}, // handling the promise rejection function (dismiss) { if (dismiss === 'timer') { console.log('Cierra a las 3 segundos') } } ) } /* ------------------------------------- Clase para el cambio del beneficiario ------------------------------------------------*/ function cambiarBeneficiario(cve_doc, modulo){ var beneficiario=""; var clave=""; if(modulo=='req'){ controladorListadoRequisicionesRemoto.getBeneficiario(cve_doc,{ callback:function(items) { ShowDelay('Cargando padron de beneficiarios...',''); if(items==null){ beneficiario = ""; clave= ""; } else{ beneficiario = getHTML(items.BENEFICIARIO); clave= getHTML(items.CLV_BENEFI); } html ='<table width="400" border="0" cellspacing="0" cellpadding="0" alingn="center">'+ '<tr>'+ '<td height="20"><strong>Requisición:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+items.NUM_REQ+'</td>'+ '</tr>'+ '<tr>'+ '<td height="20"><strong>Beneficiario:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20"><input type="text" id="txtbeneficiario" value="'+beneficiario+'" style="width:400px"/><input type="hidden" id="CVE_BENE" value="'+clave+'"/></td>'+ '</tr>'+ '<tr>' + '</tr>'+ '<td height="20">&nbsp;</td>'+ '<tr>'+ '<td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="Cancelar" id="cmdcancelar" onclick="$.alerts._hide();" style="width:100px"/></td>'+ '</tr>'+ '</table>'; //_closeDelay(); swal(html,'Cambio de beneficiario', '','',0); $('#cmdaplicar').click(function(event){_cambiarBeneficiarioRequisicion(cve_doc);}) getBeneficiarios('txtbeneficiario','CVE_BENE',''); } , errorHandler:function(errorString, exception) { swal('No se ha podido leer el beneficiario del documento, esta opcion no es valida para las requisiciones - '+errorString,'Error'); } }); } if(modulo=='ped'){ controladorPedidos.getBeneficiario(cve_doc,{ callback:function(items) { ShowDelay('Cargando padrón de beneficiarios...',''); if(items==null){ beneficiario = ""; clave= ""; } else{ beneficiario = getHTML(items.BENEFICIARIO); clave= getHTML(items.CLV_BENEFI); } html ='<table width="400" border="0" cellspacing="0" cellpadding="0" alingn="center">'+ '<tr>'+ '<td height="20"><strong>Num. Pedido:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+items.NUM_PED+'</td>'+ '</tr>'+ '<tr>'+ '<td height="20"><strong>Beneficiario:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20"><input type="text" id="txtbeneficiario" value="'+beneficiario+'" style="width:400px"/><input type="hidden" id="CVE_BENE" value="'+clave+'"/></td>'+ '</tr>'+ '<tr>' + '</tr>'+ '<td height="20">&nbsp;</td>'+ '<tr>'+ '<td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="Cancelar" id="cmdcancelar" onclick="$.alerts._hide();" style="width:100px"/></td>'+ '</tr>'+ '</table>'; //_closeDelay(); jWindow(html,'Cambio de beneficiario', '','',0); $('#cmdaplicar').click(function(event){_cambiarBeneficiarioPedidos(cve_doc);}) getBeneficiarios('txtbeneficiario','CVE_BENE',''); } , errorHandler:function(errorString, exception) { swal("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } if(modulo=='op'){ controladorOrdenPagoRemoto.getBeneficiario(cve_doc,{ callback:function(items) { ShowDelay('Cargando padrón de beneficiarios...',''); if(items==null){ beneficiario = ""; clave= ""; } else{ beneficiario = getHTML(items.BENEFICIARIO); clave= getHTML(items.CLV_BENEFI); } html ='<table width="400" border="0" cellspacing="0" cellpadding="0" alingn="center">'+ '<tr>'+ '<td height="20"><strong>Num. Orden Pago:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+items.NUM_OP+'</td>'+ '</tr>'+ '<tr>'+ '<td height="20"><strong>Beneficiario:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20"><input type="text" id="txtbeneficiario" value="'+beneficiario+'" style="width:400px"/><input type="hidden" id="CVE_BENE" value="'+clave+'"/></td>'+ '</tr>'+ '<tr>' + '</tr>'+ '<td height="20">&nbsp;</td>'+ '<tr>'+ '<td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="Cancelar" id="cmdcancelar" onclick="$.alerts._hide();" style="width:100px"/></td>'+ '</tr>'+ '</table>'; //_closeDelay(); jWindow(html,'Cambio de beneficiario', '','',0); $('#cmdaplicar').click(function(event){_cambiarBeneficiarioOrdenPago(cve_doc);}) getBeneficiarios('txtbeneficiario','CVE_BENE',''); } , errorHandler:function(errorString, exception) { swal("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } if(modulo=='val'){ controladorListadoValesRemoto.getBeneficiarioVale(cve_doc,{ callback:function(items) { ShowDelay('Cargando padrón de beneficiarios...',''); if(items==null){ beneficiario = ""; clave= ""; } else{ beneficiario = getHTML(items.BENEFICIARIO); clave= getHTML(items.CLV_BENEFI); } html ='<table width="400" border="0" cellspacing="0" cellpadding="0" alingn="center">'+ '<tr>'+ '<td height="20"><strong>Num. Vale:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+items.NUM_VALE+'</td>'+ '</tr>'+ '<tr>'+ '<td height="20"><strong>Beneficiario:</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20"><input type="text" id="txtbeneficiario" value="'+beneficiario+'" style="width:400px"/><input type="hidden" id="CVE_BENE" value="'+clave+'"/></td>'+ '</tr>'+ '<tr>' + '</tr>'+ '<td height="20">&nbsp;</td>'+ '<tr>'+ '<td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="Cancelar" id="cmdcancelar" onclick="$.alerts._hide();" style="width:100px"/></td>'+ '</tr>'+ '</table>'; _closeDelay(); jWindow(html,'Cambio de beneficiario', '','',0); $('#cmdaplicar').click(function(event){_cambiarBeneficiarioVale(cve_doc);}) getBeneficiarios('txtbeneficiario','CVE_BENE',''); } , errorHandler:function(errorString, exception) { swal("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } } function _cambiarBeneficiarioVale(cve_doc){ var cve_benefi = $('#CVE_BENE').attr('value'); if(cve_benefi==''){swal('Es necesario especificar el nuevo beneficiario para continuar','Alerta'); return false;} jConfirm('¿Confirma que desea cambiar el beneficiario del documento actual?','Confirmar', function(r){ if(r){ ShowDelay('Cambiando beneficiario...', ''); controladorListadoValesRemoto.cambiarBeneficiario(cve_doc, cve_benefi,{ callback:function(items) { if(items!=null){ CloseDelay('Se ha cambiado el beneficiario con exito', 3000, function(){ setTimeout('getVale()', 1000); }); } }, errorHandler:function(errorString, exception) { swal(errorString, 'Error'); } }); } }); } function _cambiarBeneficiarioOrdenPago(cve_doc){ var cve_benefi = $('#CVE_BENE').val(); if(cve_benefi==''){swal('Es necesario especificar el nuevo beneficiario para continuar','Alerta'); return false;} jConfirm('¿Confirma que desea cambiar el beneficiario del documento actual?','Confirmar', function(r){ if(r){ ShowDelay('Cambiando beneficiario...', ''); controladorOrdenPagoRemoto.cambiarBeneficiario(cve_doc, cve_benefi,{ callback:function(items) { if(items!=null){ CloseDelay('Se ha cambiado el beneficiario con exito', 3000, function(){ setTimeout('getOrden()', 1000); }); } }, errorHandler:function(errorString, exception) { swal(errorString, 'Error'); } }); } }); } function _cambiarBeneficiarioPedidos(cve_doc){ var cve_benefi = $('#CVE_BENE').attr('value'); if(cve_benefi==''){swal('Es necesario especificar el nuevo beneficiario para continuar','Alerta'); return false;} jConfirm('¿Confirma que desea cambiar el beneficiario del documento actual?','Confirmar', function(r){ if(r){ ShowDelay('Cambiando beneficiario...', ''); controladorPedidos.cambiarBeneficiario(cve_doc, cve_benefi,{ callback:function(items) { if(items!=null){ CloseDelay('Se ha cambiado el beneficiario con exito', 3000, function(){ setTimeout('getPedidos()', 1000); }); } }, errorHandler:function(errorString, exception) { swal(errorString, 'Error'); } }); } }); } function _cambiarBeneficiarioRequisicion(cve_doc){ var cve_benefi = $('#CVE_BENE').val(); if(cve_benefi==''){swal('Es necesario especificar el nuevo beneficiario para continuar','Alerta'); return false;} jConfirm('¿Confirma que desea cambiar el beneficiario del documento actual?','Confirmar', function(r){ if(r){ ShowDelay('Cambiando beneficiario...', ''); controladorListadoRequisicionesRemoto.cambiarBeneficiario(cve_doc, cve_benefi,{ callback:function(items) { if(items!=null){ CloseDelay('Se ha cambiado el beneficiario con exito', 3000, function(){ setTimeout('getListaReq()', 1000); }); } }, errorHandler:function(errorString, exception) { swal(errorString, 'Error'); } }); } }); } /************************************************ function para cambiar el usuario de un documento *********************************************************************************/ function cambiarUsuarioDocumento(cve_doc, modulo, cve_pers){ var smodulo = ""; if(modulo=='req') smodulo = "Requisiciones"; if(modulo=='ped') smodulo = "Pedidos"; if(modulo=='op') smodulo = "Ordenes de Pago"; if(modulo=='val') smodulo = "Vales"; if(modulo=='req'){ var chkReq = []; var chkNumReq = []; $('input[name=chkrequisiciones]:checked').each(function(){chkReq.push($(this).val()); chkNumReq.push($(this).attr('alt')); }); if(chkReq.length<=0) { $('input[name=chkrequisiciones]').each(function(){if($(this).val()==cve_doc) {chkNumReq.push($(this).attr('alt')); return false;} }); chkReq.push(cve_doc); } controladorListadoRequisicionesRemoto.getListUsuarios(cve_pers,{ callback:function(items) { if(items!=null) { html = '<table width="500" class="table" border="0" cellspacing="0" cellpadding="0">'+ '<tr>'+ ' <td width="474"><span style="font-size:12px"><I><strong>Nota:</strong> Los documentos seleccionados se van a transferir a otro usario, esto puede hacer que deje de visualizarlos en los listados que le corresponden.</span></I></td>'+ ' </tr>'+ '<tr>'+ '<td height="20"><strong>'+((chkReq.length==1) ? 'Número de Requisición':'Grupo de Requisiciones:')+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+((chkNumReq.length==0) ? 'CVE_REQ: '+cve_doc:chkNumReq)+'</td>'+ '</tr>'+ ' <tr>'+ '<td><strong>Seleccione un usuario de destino:</strong></td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<select id="cbousuarios" style="width:400px">'+items+ ' </select>'+ ' </td>'+ ' </tr>'+ '<tr>'+ '<td>&nbsp;</td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="cancel" id="cancel" onclick="$.alerts._hide();" style="width:100px"/></td>'+ ' </tr>'+ '</table>'; swal('Mover documento a otro usuario',html,'Mover documento a otro usuario'); $('#cmdaplicar').click(function(event){_cambiarUsuarioRequisicion(chkReq,cve_doc);}) } } , errorHandler:function(errorString, exception) { swal("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); }/*Cierra el modulo para requisiciones*/ if(modulo=='ped'){ var chkPed = []; var chkNumPed = []; $('input[name=chkpedidos]:checked').each(function(){chkPed.push($(this).val()); chkNumPed.push($(this).attr('alt')); }); if(chkPed.length<=0) { $('input[name=chkpedidos]').each(function(){if($(this).val()==cve_doc) {chkNumPed.push($(this).attr('alt')); return false;} }); chkPed.push(cve_doc); } controladorPedidos.getListUsuarios(cve_pers,{ callback:function(items) { if(items!=null) { html = '<table width="500" border="0" cellspacing="0" cellpadding="0">'+ '<tr>'+ ' <td width="474"><span style="font-size:12px"><I><strong>Nota:</strong> Los documentos seleccionados se van a transferir a otro usario, esto puede hacer que deje de visualizarlos en los listados que le corresponden.</span></I></td>'+ ' </tr>'+ '<tr>'+ '<td height="20"><strong>'+((chkPed.length==1) ? 'Número de Pedido':'Grupo de Pedidos:')+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+((chkNumPed.length==0) ? 'CVE_PED: '+cve_doc:chkNumPed)+'</td>'+ '</tr>'+ ' <tr>'+ '<td><strong>Seleccione un usuario de destino:</strong></td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<select id="cbousuarios" style="width:500px">'+items+ ' </select>'+ ' </td>'+ ' </tr>'+ '<tr>'+ '<td>&nbsp;</td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="Cancelar" id="cmdcancelar" onclick="$.alerts._hide();" style="width:100px"/></td>'+ ' </tr>'+ '</table>'; jWindow(html,'Mover documento a otro usuario', '','',0); $('#cmdaplicar').click(function(event){_cambiarUsuarioPedidos(chkPed,cve_doc);}) } } , errorHandler:function(errorString, exception) { jError("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } if(modulo=='op'){ var chkOp = []; var chkNumOp = []; $('input[name=chkordenes]:checked').each(function(){chkOp.push($(this).val()); chkNumOp.push($(this).attr('alt')); }); if(chkOp.length<=0) { $('input[name=chkordenes]').each(function(){if($(this).val()==cve_doc) {chkNumOp.push($(this).attr('alt')); return false;} }); chkOp.push(cve_doc); } controladorOrdenPagoRemoto.getListUsuarios(cve_pers,{ callback:function(items) { if(items!=null) { html = '<table width="500" border="0" cellspacing="0" cellpadding="0">'+ '<tr>'+ ' <td width="474"><span style="font-size:12px"><I><strong>Nota:</strong> Los documentos seleccionados se van a transferir a otro usario, esto puede hacer que deje de visualizarlos en los listados que le corresponden.</span></I></td>'+ ' </tr>'+ '<tr>'+ '<td height="20"><strong>'+((chkOp.length==1) ? 'Orden de Pago':'Grupo de Orden(es) de Pago:')+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+((chkNumOp.length==0) ? 'CVE_OP: '+cve_doc:chkNumOp)+'</td>'+ '</tr>'+ ' <tr>'+ '<td><strong>Seleccione un usuario de destino:</strong></td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<select id="cbousuarios" style="width:500px">'+items+ ' </select>'+ ' </td>'+ ' </tr>'+ '<tr>'+ '<td>&nbsp;</td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="Cancelar" id="cmdcancelar" onclick="$.alerts._hide();" style="width:100px"/></td>'+ ' </tr>'+ '</table>'; swal(html,'Mover documento a otro usuario', '','',0); $('#cmdaplicar').click(function(event){_cambiarUsuarioOrdenPago(chkOp,cve_doc);}) } } , errorHandler:function(errorString, exception) { swal("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } if(modulo=='val'){ var chkVal = []; var chkNumVal = []; $('input[name=claves]:checked').each(function(){chkVal.push($(this).val()); chkNumVal.push($(this).attr('alt')); }); if(chkVal.length<=0) { $('input[name=claves]').each(function(){if($(this).val()==cve_doc) {chkNumVal.push($(this).attr('alt')); return false;} }); chkVal.push(cve_doc); } controladorListadoValesRemoto.getListUsuarios(cve_pers,{ callback:function(items) { if(items!=null) { html = '<table width="500" border="0" cellspacing="0" cellpadding="0">'+ '<tr>'+ ' <td width="474"><span style="font-size:12px"><I><strong>Nota:</strong> Los documentos seleccionados se van a transferir a otro usario, esto puede hacer que deje de visualizarlos en los listados que le corresponden.</span></I></td>'+ ' </tr>'+ '<tr>'+ '<td height="20"><strong>'+((chkVal.length==1) ? 'Número de Vale':'Grupo de Vales:')+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="20">'+((chkNumVal.length==0) ? 'CVE_VALE: '+cve_doc:chkNumVal)+'</td>'+ '</tr>'+ ' <tr>'+ '<td><strong>Seleccione un usuario de destino:</strong></td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<select id="cbousuarios" style="width:500px">'+items+ ' </select>'+ ' </td>'+ ' </tr>'+ '<tr>'+ '<td>&nbsp;</td>'+ ' </tr>'+ ' <tr>'+ ' <td align="center"><input type="button" class="botones" value="Aplicar cambios" id="cmdaplicar" style="width:100px"/> <input type="button" class="botones" value="Cancelar" id="cmdcancelar" onclick="$.alerts._hide();" style="width:100px"/></td>'+ ' </tr>'+ '</table>'; jWindow(html,'Mover documento a otro usuario', '','',0); $('#cmdaplicar').click(function(event){_cambiarUsuarioVales(chkVal,cve_doc);}) } } , errorHandler:function(errorString, exception) { jError("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } } function _cambiarUsuarioVales(chkVal, cve_doc){ var cve_pers_dest = $('#cbousuarios').val(); if(cve_pers_dest==0){jAlert('Es necesario seleccionar un usuario para realizar esta operación', 'Advertencia'); return false;} jConfirm('¿Confirma que desea mover los Vales seleccionados al usuario especificado?', 'Confirmar', function(r){ if(r){ ShowDelay('Moviendo documentos...', ''); controladorListadoValesRemoto.moverVales(chkVal, cve_pers_dest,{ callback:function(items) { if(items!=null){ CloseDelay('Se han movido los documentos con exito', 3000, function(){ setTimeout('getVale()', 1000); }); } else jError('La operacion ha fallado al mover los documentos a otro usuario', 'Error inesperado'); }, errorHandler:function(errorString, exception) { jError("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } }); } function _cambiarUsuarioPedidos(chkPed, cve_doc){ var cve_pers_dest = $('#cbousuarios').val(); if(cve_pers_dest==0){jAlert('Es necesario seleccionar un usuario para realizar esta operació³n', 'Advertencia'); return false;} jConfirm('¿Confirma que desea mover los Pedidos seleccionados al usuario especificado?', 'Confirmar', function(r){ if(r){ ShowDelay('Moviendo documentos...', ''); controladorPedidos.moverPedidos(chkPed, cve_pers_dest,{ callback:function(items) { if(items!=null){ CloseDelay('Se han movido los documentos con exito', 3000, function(){ setTimeout('getPedidos()', 1000); }); } else jError('La operacion ha fallado al mover los documentos a otro usuario', 'Error inesperado'); }, errorHandler:function(errorString, exception) { jError("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } }); } function _cambiarUsuarioRequisicion(chkReq, cve_doc){ var cve_pers_dest = $('#cbousuarios').val(); var inputOptions = $('#cbousuarios').val(); if(cve_pers_dest==0){swal('Es necesario seleccionar un usuario para realizar esta operación', 'Advertencia'); return false;} /*Empieza*/ swal({ title: '¿Esta seguro?', text: "Los cambios no se podran revertir!", timer: 3000, type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Sí, modificar', cancelButtonText: 'No, cancelar!', confirmButtonClass: 'btn btn-success', cancelButtonClass: 'btn btn-danger', buttonsStyling: false }).then(function (r) { if(r){ controladorListadoRequisicionesRemoto.moverRequisiciones(chkReq, cve_pers_dest,{ callback:function(items) { if(items!=null) { /*swal('Se han movido los documentos con exito', 3000, function(){ setTimeout('getListaReq()', 1000); });*/ swal.showLoading() getListaReq() } else swal('La operacion ha fallado al mover los documentos a otro usuario', 'Error inesperado'); }, errorHandler:function(errorString, exception) { swal("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } swal('Modificado','Se actualizo el usuario correctamente.','success') }, function (dismiss) { // dismiss can be 'cancel', 'overlay', // 'close', and 'timer' if (dismiss === 'cancel') { swal( 'Cancelled', 'Your imaginary file is safe :)', 'error' ) } }) /*Termina*/ } function _cambiarUsuarioOrdenPago(chkOp, cve_doc){ var cve_pers_dest = $('#cbousuarios').val(); if(cve_pers_dest==0){jAlert('Es necesario seleccionar un usuario para realizar esta operación', 'Advertencia'); return false;} jConfirm('¿Confirma que desea mover las Ordenes de Pago seleccionadas al usuario especificado?', 'Confirmar', function(r){ if(r){ ShowDelay('Moviendo documentos...', ''); controladorOrdenPagoRemoto.moverOrdenesPago(chkOp, cve_pers_dest,{ callback:function(items) { if(items!=null) { CloseDelay('Se han movido los documentos con exito', 3000, function(){ setTimeout('getOrden()', 1000); }); } else jError('La operacion ha fallado al mover los documentos a otro usuario', 'Error inesperado'); }, errorHandler:function(errorString, exception) { jError("Fallo la operacion:<br>Error::"+errorString+"-message::"+exception.message+"-JavaClass::"+exception.javaClassName+".<br>Consulte a su administrador"); } }); } }); } /************************************** Funcion para el cambio de fecha y periodo ******************************************************************/ /**************************************Submenu de opciones módulo Requisiciones ********************************************************************/ function cambiarFechaPeriodo(cve_doc, modulo){ var smodulo = ""; if(modulo=='req') smodulo = "Requisiciones"; if(modulo=='ped') smodulo = "Pedidos"; if(modulo=='op') smodulo ="Ordenes de Pago"; if(modulo=='val') smodulo ="Vales"; /*investigar el periodo y fecha actual del documento*/ if(modulo=='req'){ controladorListadoRequisicionesRemoto.getFechaPeriodoRequisicion(cve_doc, { callback:function(items) { var html = '<table width="350" border="0" cellspacing="0" cellpadding="0">' + '<tr>'+ '<td height="20">Número Requisición:</td>'+ '<td><strong>'+items.NUM_REQ+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="30" width="150">Periodo actual: </td>'+ '<td width="200" height="30"><select name ="cboperiodo" id="cboperiodo" style="width:140px">'+ '<option value="1" '+((items.PERIODO==1) ? 'Selected':'')+'>(01) Enero</option>'+ '<option value="2" '+((items.PERIODO==2) ? 'Selected':'')+'>(02) Febrero</option>'+ '<option value="3" '+((items.PERIODO==3) ? 'Selected':'')+'>(03) Marzo</option>'+ '<option value="4" '+((items.PERIODO==4) ? 'Selected':'')+'>(04) Abril</option>'+ '<option value="5" '+((items.PERIODO==5) ? 'Selected':'')+'>(05) Mayo</option>'+ '<option value="6" '+((items.PERIODO==6) ? 'Selected':'')+'>(06) Junio</option>'+ '<option value="7" '+((items.PERIODO==7) ? 'Selected':'')+'>(07) Julio</option>'+ '<option value="8" '+((items.PERIODO==8) ? 'Selected':'')+'>(08) Agosto</option>'+ '<option value="9" '+((items.PERIODO==9) ? 'Selected':'')+'>(09) Septiembre</option>'+ '<option value="10" '+((items.PERIODO==10) ? 'Selected':'')+'>(10) Octubre</option>'+ '<option value="11" '+((items.PERIODO==11) ? 'Selected':'')+'>(11) Noviembre</option>'+ '<option value="12" '+((items.PERIODO==12) ? 'Selected':'')+'>(12) Diciembre</option>'+ '</select></td>'+ '</tr>'+ '<tr>'+ '<td height="30">Fecha actual dd/mm/aaaa:</td>'+ '<td><input type="text" id="txtfechaactual" value="'+items.FECHA+'" style="width:140px" /></td>'+ '</tr>'+ '<tr>'+ '<td height="50" align="center" colspan="2"><input type="button" value="Aplicar cambios" id="cmdaplicar" class="botones" style="width:100px"/>&nbsp;<input type="button" value="Cancelar" id="cmdcancelar" class="botones" style="width:100px"/></td>'+ '</tr>'+ '</table>'; jWindow(html,'Cambio de fecha y periodo en '+smodulo, '','',0); if(modulo=='req') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoRequisicion(cve_doc);}) if(modulo=='op') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoOp(cve_doc);}) $('#cmdcancelar').click(function(event){$.alerts._hide();}) $('#txtfechaactual').keypress(function(event){if (event.keyCode == '13'){$('#cmdaplicar').click();}}); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } if(modulo=='ped'){ controladorPedidos.getFechaPeriodoPedido(cve_doc, { callback:function(items) { var html = '<table width="350" border="0" cellspacing="0" cellpadding="0">' + '<tr>'+ '<td height="30">Número Pedido:</td>'+ '<td><strong>'+items.NUM_PED+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="30">Fecha actual dd/mm/aaaa:</td>'+ '<td><input type="text" id="txtfechaactual" value="'+items.FECHA_PED+'" style="width:140px" /></td>'+ '</tr>'+ '<tr>'+ '<td height="50" align="center" colspan="2"><input type="button" value="Aplicar cambios" id="cmdaplicar" class="botones" style="width:100px"/>&nbsp;<input type="button" value="Cancelar" id="cmdcancelar" class="botones" style="width:100px"/></td>'+ '</tr>'+ '</table>'; jWindow(html,'Cambio de fecha en '+smodulo, '','',0); if(modulo=='req') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoRequisicion(cve_doc);}) if(modulo=='ped') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoPedido(cve_doc);}) if(modulo=='op') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoOp(cve_doc);}) $('#cmdcancelar').click(function(event){$.alerts._hide();}) $('#txtfechaactual').keypress(function(event){if (event.keyCode == '13'){$('#cmdaplicar').click();}}); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } if(modulo=='op'){ controladorOrdenPagoRemoto.getFechaPeriodoOp(cve_doc, { callback:function(items) { var html = '<table width="350" border="0" cellspacing="0" cellpadding="0">' + '<tr>'+ '<td height="30">Número Orden de Pago:</td>'+ '<td><strong>'+items.NUM_OP+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="30" width="150">Periodo actual: </td>'+ '<td width="200"><select name ="cboperiodo" id="cboperiodo" style="width:140px">'+ '<option value="1" '+((items.PERIODO==1) ? 'Selected':'')+'>(01) Enero</option>'+ '<option value="2" '+((items.PERIODO==2) ? 'Selected':'')+'>(02) Febrero</option>'+ '<option value="3" '+((items.PERIODO==3) ? 'Selected':'')+'>(03) Marzo</option>'+ '<option value="4" '+((items.PERIODO==4) ? 'Selected':'')+'>(04) Abril</option>'+ '<option value="5" '+((items.PERIODO==5) ? 'Selected':'')+'>(05) Mayo</option>'+ '<option value="6" '+((items.PERIODO==6) ? 'Selected':'')+'>(06) Junio</option>'+ '<option value="7" '+((items.PERIODO==7) ? 'Selected':'')+'>(07) Julio</option>'+ '<option value="8" '+((items.PERIODO==8) ? 'Selected':'')+'>(08) Agosto</option>'+ '<option value="9" '+((items.PERIODO==9) ? 'Selected':'')+'>(09) Septiembre</option>'+ '<option value="10" '+((items.PERIODO==10) ? 'Selected':'')+'>(10) Octubre</option>'+ '<option value="11" '+((items.PERIODO==11) ? 'Selected':'')+'>(11) Noviembre</option>'+ '<option value="12" '+((items.PERIODO==12) ? 'Selected':'')+'>(12) Diciembre</option>'+ '</select></td>'+ '</tr>'+ '<tr>'+ '<td height="30">Fecha actual dd/mm/aaaa:</td>'+ '<td><input type="text" id="txtfechaactual" value="'+items.FECHA+'" style="width:140px" /></td>'+ '</tr>'+ '<tr>'+ '<td height="50" align="center" colspan="2"><input type="button" value="Aplicar cambios" id="cmdaplicar" class="botones" style="width:100px"/>&nbsp;<input type="button" value="Cancelar" id="cmdcancelar" class="botones" style="width:100px"/></td>'+ '</tr>'+ '</table>'; jWindow(html,'Cambio de fecha y periodo en '+smodulo, '','',0); if(modulo=='req') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoRequisicion(cve_doc);}) if(modulo=='op') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoOp(cve_doc);}) $('#cmdcancelar').click(function(event){$.alerts._hide();}) $('#txtfechaactual').keypress(function(event){if (event.keyCode == '13'){$('#cmdaplicar').click();}}); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } if(modulo=='val'){ controladorListadoValesRemoto.getFechaPeriodoVale(cve_doc, { callback:function(items) { var html = '<table width="350" border="0" cellspacing="0" cellpadding="0">' + '<tr>'+ '<td height="30">Numero Vale:</td>'+ '<td><strong>'+items.NUM_VALE+'</strong></td>'+ '</tr>'+ '<tr>'+ '<td height="30" width="150">Periodo actual: </td>'+ '<td width="200"><select name ="cboperiodo" id="cboperiodo" style="width:140px">'+ '<option value="1" '+((items.MES==1) ? 'Selected':'')+'>(01) Enero</option>'+ '<option value="2" '+((items.MES==2) ? 'Selected':'')+'>(02) Febrero</option>'+ '<option value="3" '+((items.MES==3) ? 'Selected':'')+'>(03) Marzo</option>'+ '<option value="4" '+((items.MES==4) ? 'Selected':'')+'>(04) Abril</option>'+ '<option value="5" '+((items.MES==5) ? 'Selected':'')+'>(05) Mayo</option>'+ '<option value="6" '+((items.MES==6) ? 'Selected':'')+'>(06) Junio</option>'+ '<option value="7" '+((items.MES==7) ? 'Selected':'')+'>(07) Julio</option>'+ '<option value="8" '+((items.MES==8) ? 'Selected':'')+'>(08) Agosto</option>'+ '<option value="9" '+((items.MES==9) ? 'Selected':'')+'>(09) Septiembre</option>'+ '<option value="10" '+((items.MES==10) ? 'Selected':'')+'>(10) Octubre</option>'+ '<option value="11" '+((items.MES==11) ? 'Selected':'')+'>(11) Noviembre</option>'+ '<option value="12" '+((items.MES==12) ? 'Selected':'')+'>(12) Diciembre</option>'+ '</select></td>'+ '</tr>'+ '<tr>'+ '<td height="30">Fecha actual dd/mm/aaaa:</td>'+ '<td><input type="text" id="txtfechaactual" value="'+items.FECHA+'" style="width:140px" /></td>'+ '</tr>'+ '<tr>'+ '<td height="50" align="center" colspan="2"><input type="button" value="Aplicar cambios" id="cmdaplicar" class="botones" style="width:100px"/>&nbsp;<input type="button" value="Cancelar" id="cmdcancelar" class="botones" style="width:100px"/></td>'+ '</tr>'+ '</table>'; jWindow(html,'Cambio de fecha y periodo en '+smodulo, '','',0); if(modulo=='req') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoRequisicion(cve_doc);}) if(modulo=='op') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoOp(cve_doc);}) if(modulo=='val') $('#cmdaplicar').click(function(event){_cambiarFechaPeriodoVal(cve_doc);}) $('#cmdcancelar').click(function(event){$.alerts._hide();}) $('#txtfechaactual').keypress(function(event){if (event.keyCode == '13'){$('#cmdaplicar').click();}}); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } } function _cambiarFechaPeriodoVal(cve_doc){ var periodo = $('#cboperiodo').val(); var fecha = $('#txtfechaactual').attr('value'); jConfirm('¿Confirma que desea aplicar los cambios para la fecha y periodo del Vale?','Confirmar', function(r){ if(r){ controladorListadoValesRemoto.cambiarFechaPeriodo(cve_doc, fecha, periodo, { callback:function(items) { if(items) CloseDelay('Fecha y periodo cambiados con éxito', 3000, setTimeout('getVale()',1000)); else jError(items, 'Error'); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } }); } function _cambiarFechaPeriodoOp(cve_doc){ var periodo = $('#cboperiodo').val(); var fecha = $('#txtfechaactual').attr('value'); jConfirm('¿Confirma que desea aplicar los cambios para la fecha y periodo de la Orden de Pago?','Confirmar', function(r){ if(r){ controladorOrdenPagoRemoto.cambiarFechaPeriodo(cve_doc, fecha, periodo, { callback:function(items) { if(items) CloseDelay('Fecha y periodo cambiados con éxito', 3000, setTimeout('getOrden()',1000)); else jError(items, 'Error'); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } }); } function _cambiarFechaPeriodoPedido(cve_doc){ var fecha = $('#txtfechaactual').attr('value'); jConfirm('¿Confirma que desea aplicar los cambios para la fecha del Pedido?','Confirmar', function(r){ if(r){ controladorPedidos.cambiarFechaPeriodo(cve_doc, fecha, { callback:function(items) { if(items) CloseDelay('Fecha cambiada con éxito', 3000, setTimeout('getPedidos()',1000)); else jError(items, 'Error'); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } }); } function _cambiarFechaPeriodoRequisicion(cve_doc){ var periodo = $('#cboperiodo').val(); var fecha = $('#txtfechaactual').attr('value'); jConfirm('¿Confirma que desea aplicar los cambios para la fecha y periodo de la Requisicion?','Confirmar', function(r){ if(r){ controladorListadoRequisicionesRemoto.cambiarFechaPeriodo(cve_doc, fecha, periodo, { callback:function(items) { if(items) CloseDelay('Fecha y periodo cambiados con éxito', 3000, setTimeout('getListaReq()',1000)); else jError(items, 'Error'); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } }); } /***********************************funcion que sirve para mostrar el submenu de opciones********************************************************/ function subOpAdm(modulo, cve_doc, cve_pers){ var titulo = ""; if(modulo=='req') titulo = 'Requisiciones'; if(modulo=='ped') titulo = 'Pedidos' if(modulo=='op') titulo = 'Ordenes de Pago'; if(modulo=='val') titulo = 'Vales'; if(modulo=='con') titulo = 'Contrato'; swal({ title: 'Submenu de opciones módulo: '+ titulo, width: 500, confirmButtonText: 'Cerrar', html: '<iframe width="400" height="220" name="subMenuAdmon" id="subMenuAdmon" frameborder="0" src="../../sam/utilerias/sumenuAdmon.action?modulo='+modulo+'&cve_doc='+cve_doc+'&cve_pers='+cve_pers+'"></iframe>', }) } function ajustesImportes(cve_doc, modulo, num_doc) { if(modulo=='ped') ajustesImportes_Pedido(cve_doc, modulo, num_doc); if(modulo=='con') ajustesImportes_Contrato(cve_doc, modulo, num_doc); if(modulo=='fac') ajustesImportes_Factura(cve_doc, modulo, num_doc); } function ajustesImportes_Pedido(cve_doc, modulo, num_doc) { var proyectos = []; var partidas = []; var html = ''; controladorPedidos.getMovimientosAjustadosPedidos(cve_doc, { callback:function(items) { html+= '<div id="divMovCaptura" style="display:none; position:absolute; top:15px; padding-bottom:10px">' +'<h1>Ajuste de Importe en Pedidos</h1>' +'<table width="400">' +'<tr><td><input id="ID_SAM_MOD_COMP" type="hidden" value="0"> <input id="CVE_PEDIDO" type="hidden" value="'+cve_doc+'"></td></tr>' +'<tr><th height="20">Proyecto:</th><td><select id="cboProyecto" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Partidas:</th><td><select id="cboPartidas" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Fecha:</th><td><input type="text" id="txtfechaactual" value="" style="width:197px"></td></tr>' +'<tr><th height="20">Importe:</th><td><input id="txtimporteMov" type="text" value="" maxlength="10" style="width:197px;" onkeypress="return keyNumbero(event);"></td></tr>' +'<tr><th height="20"></th></tr>' +'<tr><th height="20"></th><td><input type="button" style="width:100px" class="botones" value="Guardar" id="cmdGuardarAjuste">&nbsp;<input type="button" style="width:100px" class="botones" value="Cancelar" id="cmdCancelarAjuste"></td></tr>' +'</table>' +'</div>'; html+= '<div id="divMovListado"><div style="padding-bottom:5px"><input id="cmdAgregarAjuste" style="width:200px;" type="button" value="Agregar Ajuste de Importe"></div><table class="listas" width="400"><tr><th height="20">PROYECTO</th><th>PARTIDA</th><th>FECHA</th><th>IMPORTE</th><th>Opc.</th></tr>'; jQuery.each(items,function(i) { html += '<td align="center">'+this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']' +'</td><td align="center">'+this.CLV_PARTID+'</td><td>'+this.FECHA_MOVTO+'</td><td align="right">'+formatNumber(this.IMPORTE,'$')+'</td><td align="center"><img src="../../imagenes/page_white_edit.png" width="16" height="16" style="cursor:pointer" OnClick="editarConceptoAjuste('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.id_sam_mod_comp+','+this.ID_PROYECTO+',\''+this.CLV_PARTID+'\',\''+this.FECHA_MOVTO+'\',\''+this.IMPORTE+'\')" > <img id="Remover" src="../../imagenes/cross.png" width="16" height="16" style="cursor:pointer" OnClick="eliminarConceptoAjuste('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.id_sam_mod_comp+')"></td></tr>'; if(proyectos.indexOf(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']')==-1) proyectos.push(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']'); if(partidas.indexOf(this.CLV_PARTID)==-1) partidas.push(this.CLV_PARTID); }); html+='</table></div>'; jWindow(html,'Ajuste de Importe en Factura: '+num_doc, '','Cerrar',1); //Si no hay proyectos buscar en los conceptos if(proyectos.length==0) { controladorPedidos.getProyectoPartidaPedido(cve_doc, { callback:function(items) { if(proyectos.indexOf(items.ID_PROYECTO+ ' ['+items.N_PROGRAMA+']')==-1) proyectos.push(items.ID_PROYECTO+ ' ['+items.N_PROGRAMA+']'); if(partidas.indexOf(items.CLV_PARTID)==-1) partidas.push(items.CLV_PARTID); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } $('#cmdGuardarAjuste').click(function(event){ if($('#txtimporteMov').val()=='') { alert('Es necesario escribir el importe'); return false; } else guardarMovimientoAjustePedido(cve_doc, modulo, num_doc); }); $('#cmdCancelarAjuste').click(function(event){ $('#divMovListado').show(); $('#divMovCaptura').hide(); ajustesImportes(cve_doc, modulo, num_doc); }); $('#cmdAgregarAjuste').click(function(event){ var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth()+1; var curr_year = d.getFullYear(); $('#divMovListado').hide(); $('#divMovCaptura').show(); $('#popup_message_window').css('height','250px'); $('#txtfechaactual').attr('value', curr_date+'/'+(parseInt(curr_month) < 10? '0'+curr_month : curr_month)+'/'+curr_year); $.each( proyectos, function( index, value ){ $('#cboProyecto').append('<option value='+value+'>'+value+'</option>'); }); $.each( partidas, function( index, value ){ $('#cboPartidas').append('<option value='+value+'>'+value+'</option>'); }); }); $.each( proyectos, function( index, value ){ $('#cboProyecto').append('<option value='+value+'>'+value+'</option>'); }); $.each( partidas, function( index, value ){ $('#cboPartidas').append('<option value='+value+'>'+value+'</option>'); }); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } function ajustesImportes_Factura(cve_doc, modulo, num_doc) { var proyectos = []; var partidas = []; var html = ''; controladorListadoFacturasRemoto.getMovimientosAjustadosFactura(cve_doc, { callback:function(items) { html+= '<div id="divMovCaptura" style="display:none; position:absolute; top:15px; padding-bottom:10px">' +'<h1>Ajuste de Importe en Factura</h1>' +'<table width="400">' +'<tr><td><input id="ID_SAM_MOD_COMP" type="hidden" value="0"> <input id="CVE_FACTURA" type="hidden" value="'+cve_doc+'"></td></tr>' +'<tr><th height="20">Proyecto:</th><td><select id="cboProyecto" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Partidas:</th><td><select id="cboPartidas" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Fecha:</th><td><input type="text" id="txtfechaactual" value="" style="width:197px"></td></tr>' +'<tr><th height="20">Importe:</th><td><input id="txtimporteMov" type="text" value="" maxlength="10" style="width:197px;" onkeypress="return keyNumbero(event);"></td></tr>' +'<tr><th height="20"></th></tr>' +'<tr><th height="20"></th><td><input type="button" style="width:100px" class="botones" value="Guardar" id="cmdGuardarAjuste">&nbsp;<input type="button" style="width:100px" class="botones" value="Cancelar" id="cmdCancelarAjuste"></td></tr>' +'</table>' +'</div>'; html+= '<div id="divMovListado"><div style="padding-bottom:5px"><input id="cmdAgregarAjuste" style="width:200px;" type="button" value="Agregar Ajuste de Importe"></div><table class="listas" width="400"><tr><th height="20">PROYECTO</th><th>PARTIDA</th><th>FECHA</th><th>IMPORTE</th><th>Opc.</th></tr>'; jQuery.each(items,function(i) { html += '<td align="center">'+this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']' +'</td><td align="center">'+this.CLV_PARTID+'</td><td>'+this.FECHA_MOVTO+'</td><td align="right">'+formatNumber(this.IMPORTE,'$')+'</td><td align="center"><img src="../../imagenes/page_white_edit.png" width="16" height="16" style="cursor:pointer" OnClick="editarConceptoAjuste('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.id_sam_mod_comp+','+this.ID_PROYECTO+',\''+this.CLV_PARTID+'\',\''+this.FECHA_MOVTO+'\',\''+this.IMPORTE+'\')" > <img id="Remover" src="../../imagenes/cross.png" width="16" height="16" style="cursor:pointer" OnClick="eliminarConceptoAjuste('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.id_sam_mod_comp+')"></td></tr>'; if(proyectos.indexOf(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']')==-1) proyectos.push(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']'); if(partidas.indexOf(this.CLV_PARTID)==-1) partidas.push(this.CLV_PARTID); }); html+='</table></div>'; jWindow(html,'Ajuste de Importe en Factura: '+num_doc, '','Cerrar',1); //Si no hay proyectos buscar en los conceptos if(proyectos.length==0) { controladorListadoFacturasRemoto.getConceptosFactura(cve_doc, { callback:function(items) { jQuery.each(items,function(i) { if(proyectos.indexOf(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']')==-1) proyectos.push(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']'); if(partidas.indexOf(this.CLV_PARTID)==-1) partidas.push(this.CLV_PARTID); }); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } $('#cmdGuardarAjuste').click(function(event){ if($('#txtimporteMov').val()=='') { alert('Es necesario escribir el importe'); return false; } else guardarMovimientoAjusteFactura(cve_doc, modulo, num_doc); }); $('#cmdCancelarAjuste').click(function(event){ $('#divMovListado').show(); $('#divMovCaptura').hide(); ajustesImportes(cve_doc, modulo, num_doc); }); $('#cmdAgregarAjuste').click(function(event){ var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth()+1; var curr_year = d.getFullYear(); $('#divMovListado').hide(); $('#divMovCaptura').show(); $('#popup_message_window').css('height','250px'); $('#txtfechaactual').attr('value', curr_date+'/'+(parseInt(curr_month) < 10? '0'+curr_month : curr_month)+'/'+curr_year); $.each( proyectos, function( index, value ){ $('#cboProyecto').append('<option value='+value+'>'+value+'</option>'); }); $.each( partidas, function( index, value ){ $('#cboPartidas').append('<option value='+value+'>'+value+'</option>'); }); }); $.each( proyectos, function( index, value ){ $('#cboProyecto').append('<option value='+value+'>'+value+'</option>'); }); $.each( partidas, function( index, value ){ $('#cboPartidas').append('<option value='+value+'>'+value+'</option>'); }); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } function ajustesImportes_Contrato(cve_doc, modulo, num_doc) { var proyectos = []; var partidas = []; var html = ''; controladorListadoContratosRemoto.getMovimientosAjustadosContrato(cve_doc, { callback:function(items) { html+= '<div id="divMovCaptura" style="display:none; position:absolute; top:15px; padding-bottom:10px">' +'<h1>Ajuste de Importe en Contrato</h1>' +'<table width="400">' +'<tr><td><input id="ID_SAM_MOD_COMP" type="hidden" value="0"> <input id="CVE_CONTRATO" type="hidden" value="'+cve_doc+'"></td></tr>' +'<tr><th height="20">Proyecto:</th><td><select id="cboProyecto" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Partidas:</th><td><select id="cboPartidas" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Fecha:</th><td><input type="text" id="txtfechaactual" value="" style="width:197px"></td></tr>' +'<tr><th height="20">Importe:</th><td><input id="txtimporteMov" type="text" value="" maxlength="10" style="width:197px;" onkeypress="return keyNumbero(event);"></td></tr>' +'<tr><th height="20"></th></tr>' +'<tr><th height="20"></th><td><input type="button" style="width:100px" class="botones" value="Guardar" id="cmdGuardarAjusteContrato">&nbsp;<input type="button" style="width:100px" class="botones" value="Cancelar" id="cmdCancelarAjusteContrato"></td></tr>' +'</table>' +'</div>'; html+= '<div id="divMovListado"><div style="padding-bottom:5px"><input id="cmdAgregarAjusteContrato" style="width:200px;" type="button" value="Agregar Ajuste de Importe"></div><table class="listas" width="400"><tr><th height="20">PROYECTO</th><th>PARTIDA</th><th>FECHA</th><th>IMPORTE</th><th>Opc.</th></tr>'; jQuery.each(items,function(i) { html += '<td align="center">'+this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']' +'</td><td align="center">'+this.CLV_PARTID+'</td><td>'+this.FECHA_MOVTO+'</td><td align="right">'+formatNumber(this.IMPORTE,'$')+'</td><td align="center"><img src="../../imagenes/page_white_edit.png" width="16" height="16" style="cursor:pointer" OnClick="editarConceptoAjuste('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.id_sam_mod_comp+','+this.ID_PROYECTO+',\''+this.CLV_PARTID+'\',\''+this.FECHA_MOVTO+'\',\''+this.IMPORTE+'\')" > <img id="Remover" src="../../imagenes/cross.png" width="16" height="16" style="cursor:pointer" OnClick="eliminarConceptoAjuste('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.id_sam_mod_comp+')"></td></tr>'; if(proyectos.indexOf(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']')==-1) proyectos.push(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']'); if(partidas.indexOf(this.CLV_PARTID)==-1) partidas.push(this.CLV_PARTID); }); html+='</table></div>'; jWindow(html,'Ajuste de Importe en Contrato: '+num_doc, '','Cerrar',1); //Si no hay proyectos buscar en los conceptos if(proyectos.length==0) { controladorListadoContratosRemoto.getConceptosContrato(cve_doc, { callback:function(items) { jQuery.each(items,function(i) { if(proyectos.indexOf(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']')==-1) proyectos.push(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']'); if(partidas.indexOf(this.CLV_PARTID)==-1) partidas.push(this.CLV_PARTID); }); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } $('#cmdGuardarAjusteContrato').click(function(event){ if($('#txtimporteMov').val()=='') { alert('Es necesario escribir el importe'); return false; } else guardarMovimientoAjusteContrato(cve_doc, modulo, num_doc); }); $('#cmdCancelarAjusteContrato').click(function(event){ $('#divMovListado').show(); $('#divMovCaptura').hide(); ajustesImportes(cve_doc, modulo, num_doc); }); $('#cmdAgregarAjusteContrato').click(function(event){ var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth()+1; var curr_year = d.getFullYear(); $('#divMovListado').hide(); $('#divMovCaptura').show(); $('#popup_message_window').css('height','250px'); $('#txtfechaactual').attr('value', curr_date+'/'+(parseInt(curr_month) < 10? '0'+curr_month : curr_month)+'/'+curr_year); $.each( proyectos, function( index, value ){ $('#cboProyecto').append('<option value='+value+'>'+value+'</option>'); }); $.each( partidas, function( index, value ){ $('#cboPartidas').append('<option value='+value+'>'+value+'</option>'); }); }); $.each( proyectos, function( index, value ){ $('#cboProyecto').append('<option value='+value+'>'+value+'</option>'); }); $.each( partidas, function( index, value ){ $('#cboPartidas').append('<option value='+value+'>'+value+'</option>'); }); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } function editarConceptoAjuste(cve_doc, modulo, num_doc, idDetalle, idProyecto, clv_partid, fecha, importe) { $('#divMovCaptura').show(); $('#divMovListado').hide(); $('#popup_message_window').css('height','250px'); $('#ID_SAM_MOD_COMP').attr('value', idDetalle); $('#cboProyecto').val(idProyecto); $('#cboPartidas').val(clv_partid); $('#txtfechaactual').attr('value', fecha); $('#txtimporteMov').attr('value', importe); } function eliminarConceptoAjuste(cve_doc, modulo, num_doc, idConcepto) { if(modulo=='ped') { controladorPedidos.eliminarConceptoAjustePedido(idConcepto, { callback:function(items) { ajustesImportes(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } if(modulo=='fac') { controladorListadoFacturasRemoto.eliminarConceptoAjusteFactura(idConcepto, { callback:function(items) { ajustesImportes(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } if(modulo=='con') { ControladorContratosRemoto.eliminarConceptoAjusteContrato(idConcepto, { callback:function(items) { ajustesImportes(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } } function guardarMovimientoAjustePedido(cve_doc, modulo, num_doc) { controladorPedidos.guardarAjustePedidoPeredo($('#ID_SAM_MOD_COMP').attr('value'), cve_doc, $('#cboProyecto').attr('value'),$('#cboPartidas').attr('value'), $('#txtfechaactual').attr('value'), $('#txtimporteMov').attr('value'),{ callback:function(items) { ajustesImportes(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } function guardarMovimientoAjusteFactura(cve_doc, modulo, num_doc) { controladorListadoFacturasRemoto.guardarAjusteFacturaPeredo($('#ID_SAM_MOD_COMP').attr('value'), cve_doc, $('#cboProyecto').attr('value'),$('#cboPartidas').attr('value'), $('#txtfechaactual').attr('value'), $('#txtimporteMov').attr('value'),{ callback:function(items) { ajustesImportes(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } function guardarMovimientoAjusteContrato(cve_doc, modulo, num_doc) { ControladorContratosRemoto.guardarAjusteContratoPeredo($('#ID_SAM_MOD_COMP').attr('value'), $('#CVE_CONTRATO').attr('value'), $('#cboProyecto').attr('value'),$('#cboPartidas').attr('value'), $('#txtfechaactual').attr('value'), $('#txtimporteMov').attr('value'),{ callback:function(items) { ajustesImportes(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } function reduccionAmpliacion(cve_doc, modulo, num_doc) { var proyectos = []; var partidas = []; var html = ''; if(modulo=='con') { controladorListadoContratosRemoto.getConceptosContrato(cve_doc, { callback:function(items) { html+= '<div id="divMovCaptura" style="display:none; position:absolute; top:15px; padding-bottom:10px">' +'<h1>Capturar movimientos de contrato</h1>' +'<table>' +'<tr><td><input id="ID_DETALLE" type="hidden" value="0"> <input id="CVE_CONTRATO" type="hidden" value="'+cve_doc+'"></td></tr>' +'<tr><th height="20">Tipo de Movimiento:</th><td><select id="cboMovimiento" style="width:200px;"><option value="COMPROMISO">COMPROMISO</option></select></td></tr>' +'<tr><th height="20">Proyecto:</th><td><select id="cboProyecto" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Partidas:</th><td><select id="cboPartidas" style="width:200px;"></select></td></tr>' +'<tr><th height="20">Periodo:</th><td><select id="cboPeriodo" style="width:200px;"><option value="1">ENERO</option><option value="2">FEBRERO</option><option value="3">MARZO</option><option value="4">ABRIL</option><option value="5">MAYO</option><option value="6">JUNIO</option><option value="7">JULIO</option><option value="8">AGOSTO</option><option value="9">SEPTIEMBRE</option><option value="10">OCTUBRE</option><option value="11">NOVIEMBRE</option><option value="12">DICIEMBRE</option></select></td></tr>' +'<tr><th height="20">Importe:</th><td><input id="txtimporteMovCon" type="text" value="" maxlength="10" style="width:197px;" onkeypress="return keyNumbero(event);"></td></tr>' +'<tr><th height="20"></th></tr>' +'<tr><th height="20"></th><td><input type="button" style="width:100px" class="botones" value="Guardar" id="cmdGuardarMovCon">&nbsp;<input type="button" style="width:100px" class="botones" value="Cancelar" id="cmdCancelarMovCon"></td></tr>' +'</table>' +'</div>'; html+= '<div id="divMovListado"><div style="padding-bottom:5px"><input id="cmdAgregarMovCon" style="width:160px;" type="button" value="Agregar Movimiento"></div><table class="listas" width="450"><tr><th height="20">PERIODO</th><th>PROYECTO</th><th>PARTIDA</th><th>MOVIMIENTO</th><th>IMPORTE</th><th>Opc.</th></tr>'; jQuery.each(items,function(i) { html += '<tr><td height="20" align="center">'+this.DESC_PERIODO+'</td><td align="center">'+this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']' +'</td><td align="center">'+this.CLV_PARTID+'</td><td>'+this.TIPO_MOV+'</td><td align="right">'+formatNumber(this.IMPORTE,'$')+'</td><td align="center"><img src="../../imagenes/page_white_edit.png" width="16" height="16" style="cursor:pointer" OnClick="editarConceptoMovCon('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.ID_DETALLE_COMPROMISO+','+this.ID_PROYECTO+',\''+this.CLV_PARTID+'\','+this.PERIODO+',\''+this.TIPO_MOV+'\',\''+this.IMPORTE+'\')" > <img id="Remover" src="../../imagenes/cross.png" width="16" height="16" style="cursor:pointer" OnClick="eliminarConcepto('+cve_doc+',\''+modulo+'\',\''+num_doc+'\','+this.ID_DETALLE_COMPROMISO+')"></td></tr>'; if(proyectos.indexOf(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']')==-1) proyectos.push(this.ID_PROYECTO+ ' ['+this.N_PROGRAMA+']'); if(partidas.indexOf(this.CLV_PARTID)==-1) partidas.push(this.CLV_PARTID); }); html+='</table></div>'; jWindow(html,'Reducción y Ampliación de Contrato: '+num_doc, '','Cerrar',1); $('#cmdGuardarMovCon').click(function(event){ if($('#txtimporteMovCon').val()=='') { alert('Es necesario escribir el importe'); return false; } else guardarMovimientoContrato(cve_doc, modulo, num_doc); }); $('#cmdCancelarMovCon').click(function(event){ $('#divMovListado').show(); $('#divMovCaptura').hide(); reduccionAmpliacion(cve_doc, modulo, num_doc); }); $('#cmdAgregarMovCon').click(function(event){ $('#divMovListado').hide(); $('#divMovCaptura').show(); $('#cboProyecto').attr('disable', false); $('#cboPartidas').attr('disable', false); $('#popup_message_window').css('height','300px'); }); $.each( proyectos, function( index, value ){ $('#cboProyecto').append('<option value='+value+'>'+value+'</option>'); }); $.each( partidas, function( index, value ){ $('#cboPartidas').append('<option value='+value+'>'+value+'</option>'); }); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } } function editarConceptoMovCon(cve_doc, modulo, num_doc, idDetalle, idProyecto, clv_partid, periodo, tipo_mov, importe) { $('#divMovCaptura').show(); $('#divMovListado').hide(); $('#popup_message_window').css('height','300px'); $('#ID_DETALLE').attr('value', idDetalle); $('#cboMovimiento').val(tipo_mov); $('#cboPeriodo').val(periodo); $('#cboProyecto').val(idProyecto); $('#cboPartidas').val(clv_partid); $('#txtimporteMovCon').attr('value', importe); $('#cboProyecto').attr('disabled', true); $('#cboPartidas').attr('disabled', true); } function eliminarConcepto(cve_doc, modulo, num_doc, idConcepto) { var arrCon = []; arrCon.push(idConcepto); ControladorContratosRemoto.eliminarConceptosMovPeredo(cve_doc, arrCon, { callback:function(items) { reduccionAmpliacion(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } function guardarMovimientoContrato(cve_doc, modulo, num_doc) { ControladorContratosRemoto.guardarConceptoMovPeredo($('#ID_DETALLE').attr('value'), $('#CVE_CONTRATO').attr('value'), $('#cboProyecto').attr('value'),$('#cboPartidas').attr('value'), $('#cboPeriodo').attr('value'), $('#txtimporteMovCon').attr('value'),{ callback:function(items) { reduccionAmpliacion(cve_doc, modulo, num_doc); } , errorHandler:function(errorString, exception) { jError(errorString, 'Error'); } }); } /********************* funcion para mostrar los documetos comprometidos y precomprometidos **************************************************************************/ function mostrarConsultaCompromiso(idproyecto, proyecto, partida, periodo, consulta){ if(proyecto==""||partida==""||consulta==""){ swal('Programa y partida no validos', 'Consulta de documentos Comprometidos y Pre-comprometidos'); return false; } //jWindow('<iframe width="680" height="360" id="ventadaCompromisos" frameborder="0" src="../../sam/consultas/muestra_compromisos.action?idproyecto='+idproyecto+'&proyecto='+proyecto+'&partida='+partida+"&periodo="+periodo+'&consulta='+consulta+'"></iframe>','Detalles presupuestales', '','Cerrar',1); swal({ title: 'Detalles presupuestales', text: 'Seleccione el nuevo grupo de firma', html: '<iframe width="680" height="360" id="ventadaCompromisos" frameborder="0" src="../../sam/consultas/muestra_compromisos.action?idproyecto='+idproyecto+'&proyecto='+proyecto+'&partida='+partida+"&periodo="+periodo+'&consulta='+consulta+'"></iframe>', width: 700, padding: 10, animation: false }); } //------------------------- Reacciona a la tecla scape para cerrar los dialogos emergentes --------------------------------------------- $(document).keyup(function (event) { if(event.keyCode==27) $.alerts._hide(); //swal.closeModal(esc); }); /*funcion para cambiar el color en la entrada a la fila de una tabla*/ function color_over(f){ row_color = $('#'+f).css("background-color"); $('#'+f).css("background-color", '#FFCC66'); } function color_out(f){ $('#'+f).css("background-color", row_color); row_color = ""; } //****************************************************** funcion para mostrar la bitacora dependiendo el doc. **************************************************// function bitacoraDocumento(cve_doc, tipo){ //Cambios para 24/08/2017 /* jWindow('<iframe width="700" height="350" id="ventadaBitacora" frameborder="0" src="../../sam/consultas/muestraBitacora.action?cve_doc='+cve_doc+'&tipo_doc='+tipo+'"></iframe>','Bitacora de Movimientos', '','Cerrar',1); */ swal({ title: 'Bitacora de Movimientos: ', width: 700, html: '<iframe width="700" height="350" id="ventadaBitacora" frameborder="0" src="../../sam/consultas/muestraBitacora.action?cve_doc='+cve_doc+'&tipo_doc='+tipo+'"></iframe>', }) } /**funcion para agregar una fila a una tabla en especifico*/ function appendNewRow(table, param){ var tabla = document.getElementById(table).tBodies[0]; var row = document.createElement("TR"); var i=0; while(i<=(param.length)-1){ row.appendChild(param[i]); i++; } tabla.appendChild(row); return tabla; } /*Funcion para construir una celda en especifico*/ function Td(texto, estilo, obj, html, colspan ){ var cell = document.createElement( "TD" ); cell.style.height='20px'; if(typeof(colspan)!='undefined') cell.colSpan= colspan; if( typeof(estilo) != 'undefined' && estilo != "" ) cell.style.cssText = estilo; if( typeof(html) != 'undefined' && html != "" ) cell.innerHTML = html; else if( typeof(obj) != 'undefined' && obj != "" ) cell.appendChild( obj ); else cell.appendChild( document.createTextNode( texto ) ); return cell; } function formatNumber(num,prefix){ num= redondeo( num ); prefix = prefix || ''; num += ''; var splitStr = num.split('.'); var splitLeft = splitStr[0]; var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : ''; var regx = /(\d+)(\d{3})/; while (regx.test(splitLeft)) { splitLeft = splitLeft.replace(regx, ' $1' + ',' + '$2'); } if( splitRight.length == 0 ) splitRight = ".00"; else if( splitRight.length == 2 ) splitRight += "0"; return prefix + splitLeft + splitRight; } function quitRow( table ){ var tabla = document.getElementById(table).tBodies[0]; var nRows = tabla.rows.length; while( tabla.rows.length > 0 ){ index_table = tabla.rows.length - 1; tabla.deleteRow( index_table ); } } function LTrim( value ) { var re = /\s*((\S+\s*)*)/; return value.replace(re, "$1"); } function RTrim( value ) { var re = /((\s*\S+)*)\s*/; return value.replace(re, "$1"); } function trim( value ) { return LTrim(RTrim(value)); } function upperCase(object) { object.value=trim(object.value.toUpperCase()); } function keyNumbero( event ){ var key = ( window.event )? event.keyCode:event.which; if( ( key > 47 && key < 58 ) || key == 45 || key == 46 || key == 8 ) return true; else return false; } function redondeo( valor ) { var resultado = Math.round(valor * 100) / 100; return resultado; } function round(value, exp) { if (typeof exp === 'undefined' || +exp === 0) return Math.round(value); value = +value; exp = +exp; if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) return NaN; // Shift value = value.toString().split('e'); value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp))); // Shift back value = value.toString().split('e'); return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)); } function getHTML( param ){ if( param != null ){ if( param == "null") return ""; else return param; }else{ return ""; } } function rellenaCeros(cad, lng){ var pattern = "00000000000000000000"; var result = ""; if ( cad=="") return cad; else result = (pattern.substring(0, lng - cad.length) + cad); return result; } //--------------------Revisando por Abraham 23/08/2017---------------------------------- // SE MUESTRA AL GUARDAR UN CONTRATO................ function ShowDelay(titulo, mensaje){ // $("#dialog").remove(); if(typeof(mensaje)=='undefined'||mensaje=='') mensaje = 'Espere un momento porfavor...'; if(titulo=='undefined'||titulo=='') titulo = 'Procesando'; //jWindow('<strong>&nbsp;<img src="../../imagenes/spinner.gif" width="32" height="32" align="absmiddle" /> '+mensaje+'</strong>', titulo, 0); swal({ title: titulo, text: mensaje, timer: 5000, onOpen: function () { swal.showLoading() } }) /*swal({ title: titulo , text: mensaje, //type: 'info', html: '<div class="loaderBox">' + '<div class="loadAnim">'+ '<div class="loadeAnim1"></div>'+ '<div class="loadeAnim2"></div>'+ '<div class="loadeAnim3"></div>'+ '</div>'+ '</div>', showConfirmButton:false })*/ } function CloseDelay(mensaje, seg, fn){ try{ _closeDelay(); if(isNaN(seg)) fn = seg; if(typeof(seg)=='undefined'||seg==0||isNaN(seg)) seg = 3000; notify(mensaje,500,seg); if(typeof(fn)!='undefined') setTimeout('executeX('+fn+')',seg); } catch(err){ err=null; } } function executeX(fn){ fn(); } function _closeDelay(){ $.alerts._hide(); } function _closeDialog(){ $("#dialog").dialog('close'); } //funcion para ejecutar una funcion al pulsar enter function keyEnter(fn){ if (window.event.keyCode==13) { fn(); }else{ return false; } } //Función que crea las notificaciones function notify(msg,speed,fadeSpeed,type){ //Borra cualquier mensaje existente $('.notify').remove(); //Si el temporizador para hacer desaparecer el mensaje está //activo, lo desactivamos. if (typeof fade != "undefined"){ clearTimeout(fade); } //Creamos la notificación con la clase (type) y el texto (msg) $('body').append('<div class="notify '+type+'" style="display:none;position:fixed;left:10"><p>'+msg+'</p></div>'); //Calculamos la altura de la notificación. notifyHeight = $('.notify').outerHeight(); //Creamos la animación en la notificación con la velocidad //que pasamos por el parametro speed $('.notify').css('top',-notifyHeight).animate({top:10,opacity:'toggle'},speed); _closeDelay(); //Creamos el temporizador para hacer desaparecer la notificación //con el tiempo almacenado en el parametro fadeSpeed fade = setTimeout(function(){ $('.notify').animate({top:notifyHeight+10,opacity:'toggle'}, speed); }, fadeSpeed); }
apache-2.0
PetrGasparik/midpoint
repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskQuartzImpl.java
108866
/* * Copyright (c) 2010-2016 Evolveum * * 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 com.evolveum.midpoint.task.quartzimpl; import com.evolveum.midpoint.prism.Containerable; import com.evolveum.midpoint.prism.Item; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.PrismContainerValue; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.PrismPropertyDefinition; import com.evolveum.midpoint.prism.PrismPropertyValue; import com.evolveum.midpoint.prism.PrismReference; import com.evolveum.midpoint.prism.PrismReferenceDefinition; import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.PrismValue; import com.evolveum.midpoint.prism.delta.ChangeType; import com.evolveum.midpoint.prism.delta.ContainerDelta; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.delta.ReferenceDelta; import com.evolveum.midpoint.prism.delta.builder.DeltaBuilder; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.builder.QueryBuilder; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.statistics.EnvironmentalPerformanceInformation; import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; import com.evolveum.midpoint.schema.statistics.ProvisioningOperation; import com.evolveum.midpoint.schema.statistics.ActionsExecutedInformation; import com.evolveum.midpoint.schema.statistics.StatisticsUtil; import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; import com.evolveum.midpoint.task.api.LightweightIdentifier; import com.evolveum.midpoint.task.api.LightweightTaskHandler; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskBinding; import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.task.api.TaskHandler; import com.evolveum.midpoint.task.api.TaskPersistenceStatus; import com.evolveum.midpoint.task.api.TaskRecurrence; import com.evolveum.midpoint.task.api.TaskRunResult; import com.evolveum.midpoint.task.api.TaskWaitingReason; import com.evolveum.midpoint.task.quartzimpl.handlers.WaitForSubtasksByPollingTaskHandler; import com.evolveum.midpoint.task.quartzimpl.handlers.WaitForTasksTaskHandler; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Future; import static com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType.F_MODEL_OPERATION_CONTEXT; import static com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType.F_WORKFLOW_CONTEXT; /** * Implementation of a Task. * * @see TaskManagerQuartzImpl * * Target state (not quite reached as for now): Functionality present in Task is related to the * data structure describing the task itself, i.e. to the embedded TaskType prism and accompanying data. * Everything related to the management of tasks is put into TaskManagerQuartzImpl and its helper classes. * * @author Radovan Semancik * @author Pavol Mederly * */ public class TaskQuartzImpl implements Task { public static final String DOT_INTERFACE = Task.class.getName() + "."; private TaskBinding DEFAULT_BINDING_TYPE = TaskBinding.TIGHT; private static final int TIGHT_BINDING_INTERVAL_LIMIT = 10; private PrismObject<TaskType> taskPrism; private PrismObject<UserType> requestee; // temporary information private EnvironmentalPerformanceInformation environmentalPerformanceInformation = new EnvironmentalPerformanceInformation(); private SynchronizationInformation synchronizationInformation; // has to be explicitly enabled private IterativeTaskInformation iterativeTaskInformation; // has to be explicitly enabled private ActionsExecutedInformation actionsExecutedInformation; // has to be explicitly enabled /** * Lightweight asynchronous subtasks. * Each task here is a LAT, i.e. transient and with assigned lightweight handler. * * This must be synchronized, because interrupt() method uses it. */ private Set<TaskQuartzImpl> lightweightAsynchronousSubtasks = Collections.synchronizedSet(new HashSet<TaskQuartzImpl>()); /* * Task result is stored here as well as in task prism. * * This one is the live value of this task's result. All operations working with this task * should work with this value. This value is explicitly updated from the value in prism * when fetching task from repo (or creating anew), see initializeFromRepo(). * * The value in taskPrism is updated when necessary, e.g. when getting taskPrism * (for example, used when persisting task to repo), etc, see the code. * * Note that this means that we SHOULD NOT get operation result from the prism - we should * use task.getResult() instead! */ private OperationResult taskResult; /** * Is the task handler allowed to run, or should it stop as soon as possible? */ private volatile boolean canRun; private TaskManagerQuartzImpl taskManager; private RepositoryService repositoryService; /** * The code that should be run for asynchronous transient tasks. * (As opposed to asynchronous persistent tasks, where the handler is specified * via Handler URI in task prism object.) */ private LightweightTaskHandler lightweightTaskHandler; /** * Future representing executing (or submitted-to-execution) lightweight task handler. */ private Future lightweightHandlerFuture; /** * An indication whether lighweight hander is currently executing or not. * Used for waiting upon its completion (because java.util.concurrent facilities are not able * to show this for cancelled/interrupted tasks). */ private volatile boolean lightweightHandlerExecuting; private static final Trace LOGGER = TraceManager.getTrace(TaskQuartzImpl.class); private static final Trace PERFORMANCE_ADVISOR = TraceManager.getPerformanceAdvisorTrace(); private TaskQuartzImpl(TaskManagerQuartzImpl taskManager) { this.taskManager = taskManager; this.canRun = true; } //region Constructors /** * Note: This constructor assumes that the task is transient. * @param taskManager * @param taskIdentifier * @param operationName if null, default op. name will be used */ TaskQuartzImpl(TaskManagerQuartzImpl taskManager, LightweightIdentifier taskIdentifier, String operationName) { this(taskManager); this.repositoryService = taskManager.getRepositoryService(); this.taskPrism = createPrism(); setTaskIdentifier(taskIdentifier.toString()); setExecutionStatusTransient(TaskExecutionStatus.RUNNABLE); setRecurrenceStatusTransient(TaskRecurrence.SINGLE); setBindingTransient(DEFAULT_BINDING_TYPE); setProgressTransient(0); setObjectTransient(null); createOrUpdateTaskResult(operationName); setDefaults(); } /** * Assumes that the task is persistent * @param operationName if null, default op. name will be used */ TaskQuartzImpl(TaskManagerQuartzImpl taskManager, PrismObject<TaskType> taskPrism, RepositoryService repositoryService, String operationName) { this(taskManager); this.repositoryService = repositoryService; this.taskPrism = taskPrism; createOrUpdateTaskResult(operationName); setDefaults(); } /** * Analogous to the previous constructor. * * @param taskPrism */ private void replaceTaskPrism(PrismObject<TaskType> taskPrism) { this.taskPrism = taskPrism; updateTaskResult(); setDefaults(); } private PrismObject<TaskType> createPrism() { try { return getPrismContext().createObject(TaskType.class); } catch (SchemaException e) { throw new SystemException(e.getMessage(), e); } } private void setDefaults() { if (getBinding() == null) { setBindingTransient(DEFAULT_BINDING_TYPE); } } private void updateTaskResult() { createOrUpdateTaskResult(null); } private void createOrUpdateTaskResult(String operationName) { OperationResultType resultInPrism = taskPrism.asObjectable().getResult(); if (resultInPrism == null) { if (operationName == null) { resultInPrism = new OperationResult(DOT_INTERFACE + "run").createOperationResultType(); } else { resultInPrism = new OperationResult(operationName).createOperationResultType(); } taskPrism.asObjectable().setResult(resultInPrism); } taskResult = OperationResult.createOperationResult(resultInPrism); } //endregion public PrismObject<TaskType> getTaskPrismObject() { if (taskResult != null) { taskPrism.asObjectable().setResult(taskResult.createOperationResultType()); taskPrism.asObjectable().setResultStatus(taskResult.getStatus().createStatusType()); } return taskPrism; } RepositoryService getRepositoryService() { return repositoryService; } void setRepositoryService(RepositoryService repositoryService) { this.repositoryService = repositoryService; } @Override public boolean isAsynchronous() { return getPersistenceStatus() == TaskPersistenceStatus.PERSISTENT || isLightweightAsynchronousTask(); // note: if it has lightweight task handler, it must be transient } private boolean recreateQuartzTrigger = false; // whether to recreate quartz trigger on next savePendingModifications and/or synchronizeWithQuartz public boolean isRecreateQuartzTrigger() { return recreateQuartzTrigger; } public void setRecreateQuartzTrigger(boolean recreateQuartzTrigger) { this.recreateQuartzTrigger = recreateQuartzTrigger; } private Collection<ItemDelta<?,?>> pendingModifications = null; public void addPendingModification(ItemDelta<?,?> delta) { if (pendingModifications == null) { pendingModifications = new ArrayList<>(); } ItemDelta.merge(pendingModifications, delta); } @Override public void addModification(ItemDelta<?,?> delta) throws SchemaException { addPendingModification(delta); delta.applyTo(taskPrism); } @Override public void addModifications(Collection<ItemDelta<?,?>> deltas) throws SchemaException { for (ItemDelta<?,?> delta : deltas) { addPendingModification(delta); delta.applyTo(taskPrism); } } @Override public void addModificationImmediate(ItemDelta<?, ?> delta, OperationResult parentResult) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException { addPendingModification(delta); delta.applyTo(taskPrism); savePendingModifications(parentResult); } @Override public void savePendingModifications(OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { if (isTransient()) { return; } if (pendingModifications != null) { synchronized (pendingModifications) { // todo perhaps we should put something like this at more places here... if (!pendingModifications.isEmpty()) { try { repositoryService.modifyObject(TaskType.class, getOid(), pendingModifications, parentResult); } finally { // todo reconsider this (it's not ideal but we need at least to reset pendingModifications to stop repeating applying this change) synchronizeWithQuartzIfNeeded(pendingModifications, parentResult); pendingModifications.clear(); } } } } if (isRecreateQuartzTrigger()) { synchronizeWithQuartz(parentResult); } } @Override public Collection<ItemDelta<?,?>> getPendingModifications() { return pendingModifications; } public void synchronizeWithQuartz(OperationResult parentResult) { taskManager.synchronizeTaskWithQuartz(this, parentResult); setRecreateQuartzTrigger(false); } private static Set<QName> quartzRelatedProperties = new HashSet<QName>(); static { quartzRelatedProperties.add(TaskType.F_BINDING); quartzRelatedProperties.add(TaskType.F_RECURRENCE); quartzRelatedProperties.add(TaskType.F_SCHEDULE); quartzRelatedProperties.add(TaskType.F_HANDLER_URI); } private void synchronizeWithQuartzIfNeeded(Collection<ItemDelta<?,?>> deltas, OperationResult parentResult) { if (isRecreateQuartzTrigger()) { synchronizeWithQuartz(parentResult); return; } for (ItemDelta<?,?> delta : deltas) { if (delta.getParentPath().isEmpty() && quartzRelatedProperties.contains(delta.getElementName())) { synchronizeWithQuartz(parentResult); return; } } } private void processModificationNow(ItemDelta<?,?> delta, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { if (delta != null) { Collection<ItemDelta<?,?>> deltas = new ArrayList<ItemDelta<?,?>>(1); deltas.add(delta); repositoryService.modifyObject(TaskType.class, getOid(), deltas, parentResult); synchronizeWithQuartzIfNeeded(deltas, parentResult); } } private void processModificationBatched(ItemDelta<?,?> delta) { if (delta != null) { addPendingModification(delta); } } /* * Getters and setters * =================== */ /* * Progress / expectedTotal */ @Override public long getProgress() { Long value = taskPrism.getPropertyRealValue(TaskType.F_PROGRESS, Long.class); return value != null ? value : 0; } @Override public void setProgress(long value) { processModificationBatched(setProgressAndPrepareDelta(value)); } @Override public void setProgressImmediate(long value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setProgressAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } @Override public void setProgressTransient(long value) { try { taskPrism.setPropertyRealValue(TaskType.F_PROGRESS, value); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } private PropertyDelta<?> setProgressAndPrepareDelta(long value) { setProgressTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_PROGRESS, value) : null; } @Override public OperationStatsType getStoredOperationStats() { return taskPrism.asObjectable().getOperationStats(); } public void setOperationStatsTransient(OperationStatsType value) { try { taskPrism.setPropertyRealValue(TaskType.F_OPERATION_STATS, value); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } public void setOperationStats(OperationStatsType value) { processModificationBatched(setOperationStatsAndPrepareDelta(value)); } private PropertyDelta<?> setOperationStatsAndPrepareDelta(OperationStatsType value) { setOperationStatsTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_OPERATION_STATS, value) : null; } @Override public Long getExpectedTotal() { Long value = taskPrism.getPropertyRealValue(TaskType.F_EXPECTED_TOTAL, Long.class); return value != null ? value : 0; } @Override public void setExpectedTotal(Long value) { processModificationBatched(setExpectedTotalAndPrepareDelta(value)); } @Override public void setExpectedTotalImmediate(Long value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setExpectedTotalAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setExpectedTotalTransient(Long value) { try { taskPrism.setPropertyRealValue(TaskType.F_EXPECTED_TOTAL, value); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } private PropertyDelta<?> setExpectedTotalAndPrepareDelta(Long value) { setExpectedTotalTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_EXPECTED_TOTAL, value) : null; } /* * Result * * setters set also result status type! */ @Override public OperationResult getResult() { return taskResult; } @Override public void setResult(OperationResult result) { processModificationBatched(setResultAndPrepareDelta(result)); setResultStatusType(result != null ? result.getStatus().createStatusType() : null); } @Override public void setResultImmediate(OperationResult result, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setResultAndPrepareDelta(result), parentResult); setResultStatusTypeImmediate(result != null ? result.getStatus().createStatusType() : null, parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void updateStoredTaskResult() throws SchemaException, ObjectNotFoundException { setResultImmediate(getResult(), new OperationResult("dummy")); } public void setResultTransient(OperationResult result) { this.taskResult = result; this.taskPrism.asObjectable().setResult(result.createOperationResultType()); setResultStatusTypeTransient(result != null ? result.getStatus().createStatusType() : null); } private PropertyDelta<?> setResultAndPrepareDelta(OperationResult result) { setResultTransient(result); if (isPersistent()) { PropertyDelta<?> d = PropertyDelta.createReplaceDeltaOrEmptyDelta(taskManager.getTaskObjectDefinition(), TaskType.F_RESULT, result != null ? result.createOperationResultType() : null); LOGGER.trace("setResult delta = " + d.debugDump()); return d; } else { return null; } } /* * Result status * * We read the status from current 'taskResult', not from prism - to be sure to get the most current value. * However, when updating, we update the result in prism object in order for the result to be stored correctly in * the repo (useful for displaying the result in task list). * * So, setting result type to a value that contradicts current taskResult leads to problems. * Anyway, result type should not be set directly, only when updating OperationResult. */ @Override public OperationResultStatusType getResultStatus() { return taskResult == null ? null : taskResult.getStatus().createStatusType(); } public void setResultStatusType(OperationResultStatusType value) { processModificationBatched(setResultStatusTypeAndPrepareDelta(value)); } public void setResultStatusTypeImmediate(OperationResultStatusType value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { processModificationNow(setResultStatusTypeAndPrepareDelta(value), parentResult); } public void setResultStatusTypeTransient(OperationResultStatusType value) { taskPrism.asObjectable().setResultStatus(value); } private PropertyDelta<?> setResultStatusTypeAndPrepareDelta(OperationResultStatusType value) { setResultStatusTypeTransient(value); if (isPersistent()) { PropertyDelta<?> d = PropertyDelta.createReplaceDeltaOrEmptyDelta(taskManager.getTaskObjectDefinition(), TaskType.F_RESULT_STATUS, value); return d; } else { return null; } } /* * Handler URI */ @Override public String getHandlerUri() { return taskPrism.getPropertyRealValue(TaskType.F_HANDLER_URI, String.class); } public void setHandlerUriTransient(String handlerUri) { try { taskPrism.setPropertyRealValue(TaskType.F_HANDLER_URI, handlerUri); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } @Override public void setHandlerUriImmediate(String value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setHandlerUriAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } @Override public void setHandlerUri(String value) { processModificationBatched(setHandlerUriAndPrepareDelta(value)); } private PropertyDelta<?> setHandlerUriAndPrepareDelta(String value) { setHandlerUriTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_HANDLER_URI, value) : null; } /* * Other handlers URI stack */ @Override public UriStack getOtherHandlersUriStack() { checkHandlerUriConsistency(); return taskPrism.asObjectable().getOtherHandlersUriStack(); } public void setOtherHandlersUriStackTransient(UriStack value) { try { taskPrism.setPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, value); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } checkHandlerUriConsistency(); } public void setOtherHandlersUriStackImmediate(UriStack value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setOtherHandlersUriStackAndPrepareDelta(value), parentResult); checkHandlerUriConsistency(); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setOtherHandlersUriStack(UriStack value) { processModificationBatched(setOtherHandlersUriStackAndPrepareDelta(value)); checkHandlerUriConsistency(); } private PropertyDelta<?> setOtherHandlersUriStackAndPrepareDelta(UriStack value) { setOtherHandlersUriStackTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_OTHER_HANDLERS_URI_STACK, value) : null; } private UriStackEntry popFromOtherHandlersUriStack() { checkHandlerUriConsistency(); UriStack stack = taskPrism.getPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, UriStack.class); // is this a live value or a copy? (should be live) if (stack == null || stack.getUriStackEntry().isEmpty()) throw new IllegalStateException("Couldn't pop from OtherHandlersUriStack, because it is null or empty"); int last = stack.getUriStackEntry().size() - 1; UriStackEntry retval = stack.getUriStackEntry().get(last); stack.getUriStackEntry().remove(last); // UriStack stack2 = taskPrism.getPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, UriStack.class); // LOGGER.info("Stack size after popping: " + stack.getUriStackEntry().size() // + ", freshly got stack size: " + stack2.getUriStackEntry().size()); setOtherHandlersUriStack(stack); return retval; } // @Override // public void pushHandlerUri(String uri) { // pushHandlerUri(uri, null, null); // } // // @Override // public void pushHandlerUri(String uri, ScheduleType schedule) { // pushHandlerUri(uri, schedule, null); // } @Override public void pushHandlerUri(String uri, ScheduleType schedule, TaskBinding binding) { pushHandlerUri(uri, schedule, binding, (Collection<ItemDelta<?,?>>) null); } @Override public void pushHandlerUri(String uri, ScheduleType schedule, TaskBinding binding, ItemDelta<?,?> delta) { Collection<ItemDelta<?,?>> deltas = null; if (delta != null) { deltas = new ArrayList<ItemDelta<?,?>>(); deltas.add(delta); } pushHandlerUri(uri, schedule, binding, deltas); } /** * Makes (uri, schedule, binding) the current task properties, and pushes current (uri, schedule, binding, extensionChange) * onto the stack. * * @param uri New Handler URI * @param schedule New schedule * @param binding New binding */ @Override public void pushHandlerUri(String uri, ScheduleType schedule, TaskBinding binding, Collection<ItemDelta<?,?>> extensionDeltas) { Validate.notNull(uri); if (binding == null) { binding = bindingFromSchedule(schedule); } checkHandlerUriConsistency(); if (this.getHandlerUri() != null) { UriStack stack = taskPrism.getPropertyRealValue(TaskType.F_OTHER_HANDLERS_URI_STACK, UriStack.class); if (stack == null) { stack = new UriStack(); } UriStackEntry use = new UriStackEntry(); use.setHandlerUri(getHandlerUri()); use.setRecurrence(getRecurrenceStatus().toTaskType()); use.setSchedule(getSchedule()); use.setBinding(getBinding().toTaskType()); if (extensionDeltas != null) { storeExtensionDeltas(use.getExtensionDelta(), extensionDeltas); } stack.getUriStackEntry().add(use); setOtherHandlersUriStack(stack); } setHandlerUri(uri); setSchedule(schedule); setRecurrenceStatus(recurrenceFromSchedule(schedule)); setBinding(binding); this.setRecreateQuartzTrigger(true); // will be applied on modifications save } public ItemDelta<?,?> createExtensionDelta(PrismPropertyDefinition definition, Object realValue) { PrismProperty<?> property = (PrismProperty<?>) definition.instantiate(); property.setRealValue(realValue); PropertyDelta propertyDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(TaskType.F_EXTENSION, property.getElementName()), definition, realValue); // PropertyDelta propertyDelta = new PropertyDelta(new ItemPath(TaskType.F_EXTENSION, property.getElementName()), definition); // propertyDelta.setValuesToReplace(PrismValue.cloneCollection(property.getValues())); return propertyDelta; } private void storeExtensionDeltas(List<ItemDeltaType> result, Collection<ItemDelta<?,?>> extensionDeltas) { for (ItemDelta itemDelta : extensionDeltas) { Collection<ItemDeltaType> deltaTypes = null; try { deltaTypes = DeltaConvertor.toItemDeltaTypes(itemDelta); } catch (SchemaException e) { throw new SystemException("Unexpected SchemaException when converting extension ItemDelta to ItemDeltaType", e); } result.addAll(deltaTypes); } } // derives default binding form schedule private TaskBinding bindingFromSchedule(ScheduleType schedule) { if (schedule == null) { return DEFAULT_BINDING_TYPE; } else if (schedule.getInterval() != null && schedule.getInterval() != 0) { return schedule.getInterval() <= TIGHT_BINDING_INTERVAL_LIMIT ? TaskBinding.TIGHT : TaskBinding.LOOSE; } else if (StringUtils.isNotEmpty(schedule.getCronLikePattern())) { return TaskBinding.LOOSE; } else { return DEFAULT_BINDING_TYPE; } } private TaskRecurrence recurrenceFromSchedule(ScheduleType schedule) { if (schedule == null) { return TaskRecurrence.SINGLE; } else if (schedule.getInterval() != null && schedule.getInterval() != 0) { return TaskRecurrence.RECURRING; } else if (StringUtils.isNotEmpty(schedule.getCronLikePattern())) { return TaskRecurrence.RECURRING; } else { return TaskRecurrence.SINGLE; } } // @Override // public void replaceCurrentHandlerUri(String newUri, ScheduleType schedule) { // // checkHandlerUriConsistency(); // setHandlerUri(newUri); // setSchedule(schedule); // } @Override public void finishHandler(OperationResult parentResult) throws ObjectNotFoundException, SchemaException { // let us drop the current handler URI and nominate the top of the other // handlers stack as the current one LOGGER.trace("finishHandler called for handler URI {}, task {}", this.getHandlerUri(), this); UriStack otherHandlersUriStack = getOtherHandlersUriStack(); if (otherHandlersUriStack != null && !otherHandlersUriStack.getUriStackEntry().isEmpty()) { UriStackEntry use = popFromOtherHandlersUriStack(); setHandlerUri(use.getHandlerUri()); setRecurrenceStatus(use.getRecurrence() != null ? TaskRecurrence.fromTaskType(use.getRecurrence()) : recurrenceFromSchedule(use.getSchedule())); setSchedule(use.getSchedule()); if (use.getBinding() != null) { setBinding(TaskBinding.fromTaskType(use.getBinding())); } else { setBinding(bindingFromSchedule(use.getSchedule())); } for (ItemDeltaType itemDeltaType : use.getExtensionDelta()) { ItemDelta itemDelta = DeltaConvertor.createItemDelta(itemDeltaType, TaskType.class, taskManager.getPrismContext()); LOGGER.trace("Applying ItemDelta to task extension; task = {}; itemDelta = {}", this, itemDelta.debugDump()); this.modifyExtension(itemDelta); } this.setRecreateQuartzTrigger(true); } else { //setHandlerUri(null); // we want the last handler to remain set so the task can be revived taskManager.closeTaskWithoutSavingState(this, parentResult); // as there are no more handlers, let us close this task } try { savePendingModifications(parentResult); checkDependentTasksOnClose(parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } LOGGER.trace("finishHandler: new current handler uri = {}, new number of handlers = {}", getHandlerUri(), getHandlersCount()); } void checkDependentTasksOnClose(OperationResult result) throws SchemaException, ObjectNotFoundException { if (getExecutionStatus() != TaskExecutionStatus.CLOSED) { return; } for (Task dependent : listDependents(result)) { ((TaskQuartzImpl) dependent).checkDependencies(result); } Task parentTask = getParentTask(result); if (parentTask != null) { ((TaskQuartzImpl) parentTask).checkDependencies(result); } } public void checkDependencies(OperationResult result) throws SchemaException, ObjectNotFoundException { if (getExecutionStatus() != TaskExecutionStatus.WAITING || getWaitingReason() != TaskWaitingReason.OTHER_TASKS) { return; } List<Task> dependencies = listSubtasks(result); dependencies.addAll(listPrerequisiteTasks(result)); LOGGER.trace("Checking {} dependencies for waiting task {}", dependencies.size(), this); for (Task dependency : dependencies) { if (!dependency.isClosed()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Dependency {} of {} is not closed (status = {})", new Object[] { dependency, this, dependency.getExecutionStatus() }); } return; } } // this could be a bit tricky, taking MID-1683 into account: // when a task finishes its execution, we now leave the last handler set // however, this applies to executable tasks; for WAITING tasks we can safely expect that if there is a handler // on the stack, we can run it (by unpausing the task) if (getHandlerUri() != null) { LOGGER.trace("All dependencies of {} are closed, unpausing the task (it has a handler defined)", this); taskManager.unpauseTask(this, result); } else { LOGGER.trace("All dependencies of {} are closed, closing the task (it has no handler defined).", this); taskManager.closeTask(this, result); } } public int getHandlersCount() { checkHandlerUriConsistency(); int main = getHandlerUri() != null ? 1 : 0; int others = getOtherHandlersUriStack() != null ? getOtherHandlersUriStack().getUriStackEntry().size() : 0; return main + others; } private boolean isOtherHandlersUriStackEmpty() { UriStack stack = taskPrism.asObjectable().getOtherHandlersUriStack(); return stack == null || stack.getUriStackEntry().isEmpty(); } private void checkHandlerUriConsistency() { if (getHandlerUri() == null && !isOtherHandlersUriStackEmpty()) throw new IllegalStateException("Handler URI is null but there is at least one 'other' handler (otherHandlerUriStack size = " + getOtherHandlersUriStack().getUriStackEntry().size() + ")"); } /* * Persistence status */ @Override public TaskPersistenceStatus getPersistenceStatus() { return StringUtils.isEmpty(getOid()) ? TaskPersistenceStatus.TRANSIENT : TaskPersistenceStatus.PERSISTENT; } // public void setPersistenceStatusTransient(TaskPersistenceStatus persistenceStatus) { // this.persistenceStatus = persistenceStatus; // } public boolean isPersistent() { return getPersistenceStatus() == TaskPersistenceStatus.PERSISTENT; } @Override public boolean isTransient() { return getPersistenceStatus() == TaskPersistenceStatus.TRANSIENT; } /* * Oid */ @Override public String getOid() { return taskPrism.getOid(); } public void setOid(String oid) { taskPrism.setOid(oid); } // obviously, there are no "persistent" versions of setOid /* * Task identifier (again, without "persistent" versions) */ @Override public String getTaskIdentifier() { return taskPrism.getPropertyRealValue(TaskType.F_TASK_IDENTIFIER, String.class); } private void setTaskIdentifier(String value) { try { taskPrism.setPropertyRealValue(TaskType.F_TASK_IDENTIFIER, value); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } /* * Execution status * * IMPORTANT: do not set this attribute explicitly (due to the need of synchronization with Quartz scheduler). * Use task life-cycle methods, like close(), suspendTask(), resumeTask(), and so on. */ @Override public TaskExecutionStatus getExecutionStatus() { TaskExecutionStatusType xmlValue = taskPrism.getPropertyRealValue(TaskType.F_EXECUTION_STATUS, TaskExecutionStatusType.class); if (xmlValue == null) { return null; } return TaskExecutionStatus.fromTaskType(xmlValue); } public void setExecutionStatusTransient(TaskExecutionStatus executionStatus) { try { taskPrism.setPropertyRealValue(TaskType.F_EXECUTION_STATUS, executionStatus.toTaskType()); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } @Override public void setInitialExecutionStatus(TaskExecutionStatus value) { if (isPersistent()) { throw new IllegalStateException("Initial execution state can be set only on transient tasks."); } taskPrism.asObjectable().setExecutionStatus(value.toTaskType()); } public void setExecutionStatusImmediate(TaskExecutionStatus value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setExecutionStatusAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setExecutionStatus(TaskExecutionStatus value) { processModificationBatched(setExecutionStatusAndPrepareDelta(value)); } private PropertyDelta<?> setExecutionStatusAndPrepareDelta(TaskExecutionStatus value) { setExecutionStatusTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_EXECUTION_STATUS, value.toTaskType()) : null; } @Override public void makeRunnable() { if (!isTransient()) { throw new IllegalStateException("makeRunnable can be invoked only on transient tasks; task = " + this); } setExecutionStatus(TaskExecutionStatus.RUNNABLE); } @Override public void makeWaiting() { if (!isTransient()) { throw new IllegalStateException("makeWaiting can be invoked only on transient tasks; task = " + this); } setExecutionStatus(TaskExecutionStatus.WAITING); } @Override public void makeWaiting(TaskWaitingReason reason) { makeWaiting(); setWaitingReason(reason); } public boolean isClosed() { return getExecutionStatus() == TaskExecutionStatus.CLOSED; } /* * Waiting reason */ @Override public TaskWaitingReason getWaitingReason() { TaskWaitingReasonType xmlValue = taskPrism.asObjectable().getWaitingReason(); if (xmlValue == null) { return null; } return TaskWaitingReason.fromTaskType(xmlValue); } public void setWaitingReasonTransient(TaskWaitingReason value) { try { taskPrism.setPropertyRealValue(TaskType.F_WAITING_REASON, value.toTaskType()); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } public void setWaitingReason(TaskWaitingReason value) { processModificationBatched(setWaitingReasonAndPrepareDelta(value)); } public void setWaitingReasonImmediate(TaskWaitingReason value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setWaitingReasonAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } private PropertyDelta<?> setWaitingReasonAndPrepareDelta(TaskWaitingReason value) { setWaitingReasonTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_WAITING_REASON, value.toTaskType()) : null; } // "safe" method @Override public void startWaitingForTasksImmediate(OperationResult result) throws SchemaException, ObjectNotFoundException { if (getExecutionStatus() != TaskExecutionStatus.WAITING) { throw new IllegalStateException("Task that has to start waiting for tasks should be in WAITING state (it is in " + getExecutionStatus() + " now)"); } setWaitingReasonImmediate(TaskWaitingReason.OTHER_TASKS, result); checkDependencies(result); } /* * Recurrence status */ public TaskRecurrence getRecurrenceStatus() { TaskRecurrenceType xmlValue = taskPrism.getPropertyRealValue(TaskType.F_RECURRENCE, TaskRecurrenceType.class); if (xmlValue == null) { return null; } return TaskRecurrence.fromTaskType(xmlValue); } @Override public boolean isSingle() { return (getRecurrenceStatus() == TaskRecurrence.SINGLE); } @Override public boolean isCycle() { // TODO: binding return (getRecurrenceStatus() == TaskRecurrence.RECURRING); } public void setRecurrenceStatus(TaskRecurrence value) { processModificationBatched(setRecurrenceStatusAndPrepareDelta(value)); } public void setRecurrenceStatusImmediate(TaskRecurrence value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setRecurrenceStatusAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setRecurrenceStatusTransient(TaskRecurrence value) { try { taskPrism.setPropertyRealValue(TaskType.F_RECURRENCE, value.toTaskType()); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } private PropertyDelta<?> setRecurrenceStatusAndPrepareDelta(TaskRecurrence value) { setRecurrenceStatusTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_RECURRENCE, value.toTaskType()) : null; } @Override public void makeSingle() { setRecurrenceStatus(TaskRecurrence.SINGLE); setSchedule(new ScheduleType()); } @Override public void makeSingle(ScheduleType schedule) { setRecurrenceStatus(TaskRecurrence.SINGLE); setSchedule(schedule); } @Override public void makeRecurring(ScheduleType schedule) { setRecurrenceStatus(TaskRecurrence.RECURRING); setSchedule(schedule); } @Override public void makeRecurringSimple(int interval) { setRecurrenceStatus(TaskRecurrence.RECURRING); ScheduleType schedule = new ScheduleType(); schedule.setInterval(interval); setSchedule(schedule); } @Override public void makeRecurringCron(String cronLikeSpecification) { setRecurrenceStatus(TaskRecurrence.RECURRING); ScheduleType schedule = new ScheduleType(); schedule.setCronLikePattern(cronLikeSpecification); setSchedule(schedule); } /* * Schedule */ @Override public ScheduleType getSchedule() { return taskPrism.asObjectable().getSchedule(); } public void setSchedule(ScheduleType value) { processModificationBatched(setScheduleAndPrepareDelta(value)); } public void setScheduleImmediate(ScheduleType value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setScheduleAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } private void setScheduleTransient(ScheduleType schedule) { taskPrism.asObjectable().setSchedule(schedule); } private PropertyDelta<?> setScheduleAndPrepareDelta(ScheduleType value) { setScheduleTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_SCHEDULE, value) : null; } /* * ThreadStopAction */ @Override public ThreadStopActionType getThreadStopAction() { return taskPrism.asObjectable().getThreadStopAction(); } @Override public void setThreadStopAction(ThreadStopActionType value) { processModificationBatched(setThreadStopActionAndPrepareDelta(value)); } public void setThreadStopActionImmediate(ThreadStopActionType value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setThreadStopActionAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } private void setThreadStopActionTransient(ThreadStopActionType value) { taskPrism.asObjectable().setThreadStopAction(value); } private PropertyDelta<?> setThreadStopActionAndPrepareDelta(ThreadStopActionType value) { setThreadStopActionTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_THREAD_STOP_ACTION, value) : null; } @Override public boolean isResilient() { ThreadStopActionType tsa = getThreadStopAction(); return tsa == null || tsa == ThreadStopActionType.RESCHEDULE || tsa == ThreadStopActionType.RESTART; } /* * Binding */ @Override public TaskBinding getBinding() { TaskBindingType xmlValue = taskPrism.getPropertyRealValue(TaskType.F_BINDING, TaskBindingType.class); if (xmlValue == null) { return null; } return TaskBinding.fromTaskType(xmlValue); } @Override public boolean isTightlyBound() { return getBinding() == TaskBinding.TIGHT; } @Override public boolean isLooselyBound() { return getBinding() == TaskBinding.LOOSE; } @Override public void setBinding(TaskBinding value) { processModificationBatched(setBindingAndPrepareDelta(value)); } @Override public void setBindingImmediate(TaskBinding value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setBindingAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setBindingTransient(TaskBinding value) { try { taskPrism.setPropertyRealValue(TaskType.F_BINDING, value.toTaskType()); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } private PropertyDelta<?> setBindingAndPrepareDelta(TaskBinding value) { setBindingTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_BINDING, value.toTaskType()) : null; } /* * Owner */ @Override public PrismObject<UserType> getOwner() { PrismReference ownerRef = taskPrism.findReference(TaskType.F_OWNER_REF); if (ownerRef == null) { return null; } return ownerRef.getValue().getObject(); } @Override public void setOwner(PrismObject<UserType> owner) { if (isPersistent()) { throw new IllegalStateException("setOwner method can be called only on transient tasks!"); } PrismReference ownerRef; try { ownerRef = taskPrism.findOrCreateReference(TaskType.F_OWNER_REF); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } ownerRef.getValue().setObject(owner); } PrismObject<UserType> resolveOwnerRef(OperationResult result) throws SchemaException { PrismReference ownerRef = taskPrism.findReference(TaskType.F_OWNER_REF); if (ownerRef == null) { throw new SchemaException("Task "+getOid()+" does not have an owner (missing ownerRef)"); } try { PrismObject<UserType> owner = repositoryService.getObject(UserType.class, ownerRef.getOid(), null, result); ownerRef.getValue().setObject(owner); return owner; } catch (ObjectNotFoundException e) { LoggingUtils.logExceptionAsWarning(LOGGER, "The owner of task {} cannot be found (owner OID: {})", e, getOid(), ownerRef.getOid()); return null; } } @Override public String getChannel() { return taskPrism.asObjectable().getChannel(); } @Override public void setChannel(String value) { processModificationBatched(setChannelAndPrepareDelta(value)); } @Override public void setChannelImmediate(String value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setChannelAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setChannelTransient(String name) { taskPrism.asObjectable().setChannel(name); } private PropertyDelta<?> setChannelAndPrepareDelta(String value) { setChannelTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_CHANNEL, value) : null; } // @Override // public String getChannel() { // PrismProperty<String> channelProperty = taskPrism.findProperty(TaskType.F_CHANNEL); // if (channelProperty == null) { // return null; // } // return channelProperty.getRealValue(); // } // @Override // public void setChannel(String channelUri) { // // TODO: Is this OK? // PrismProperty<String> channelProperty; // try { // channelProperty = taskPrism.findOrCreateProperty(TaskType.F_CHANNEL); // } catch (SchemaException e) { // // This should not happen // throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); // } // channelProperty.setRealValue(channelUri); // } /* * Object */ @Override public ObjectReferenceType getObjectRef() { PrismReference objectRef = taskPrism.findReference(TaskType.F_OBJECT_REF); if (objectRef == null) { return null; } ObjectReferenceType objRefType = new ObjectReferenceType(); objRefType.setOid(objectRef.getOid()); objRefType.setType(objectRef.getValue().getTargetType()); return objRefType; } @Override public void setObjectRef(ObjectReferenceType value) { processModificationBatched(setObjectRefAndPrepareDelta(value)); } @Override public void setObjectRef(String oid, QName type) { ObjectReferenceType objectReferenceType = new ObjectReferenceType(); objectReferenceType.setOid(oid); objectReferenceType.setType(type); setObjectRef(objectReferenceType); } @Override public void setObjectRefImmediate(ObjectReferenceType value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { processModificationNow(setObjectRefAndPrepareDelta(value), parentResult); } public void setObjectRefTransient(ObjectReferenceType objectRefType) { PrismReference objectRef; try { objectRef = taskPrism.findOrCreateReference(TaskType.F_OBJECT_REF); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } objectRef.getValue().setOid(objectRefType.getOid()); objectRef.getValue().setTargetType(objectRefType.getType()); } private ReferenceDelta setObjectRefAndPrepareDelta(ObjectReferenceType value) { setObjectRefTransient(value); PrismReferenceValue prismReferenceValue = new PrismReferenceValue(); prismReferenceValue.setOid(value.getOid()); prismReferenceValue.setTargetType(value.getType()); return isPersistent() ? ReferenceDelta.createModificationReplace(TaskType.F_OBJECT_REF, taskManager.getTaskObjectDefinition(), prismReferenceValue) : null; } @Override public String getObjectOid() { PrismReference objectRef = taskPrism.findReference(TaskType.F_OBJECT_REF); if (objectRef == null) { return null; } return objectRef.getValue().getOid(); } @Override public <T extends ObjectType> PrismObject<T> getObject(Class<T> type, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { // Shortcut PrismReference objectRef = taskPrism.findReference(TaskType.F_OBJECT_REF); if (objectRef == null) { return null; } if (objectRef.getValue().getObject() != null) { PrismObject object = objectRef.getValue().getObject(); if (object.canRepresent(type)) { return (PrismObject<T>) object; } else { throw new IllegalArgumentException("Requested object type "+type+", but the type of object in the task is "+object.getClass()); } } OperationResult result = parentResult.createSubresult(DOT_INTERFACE+"getObject"); result.addContext(OperationResult.CONTEXT_OID, getOid()); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); try { PrismObject<T> object = repositoryService.getObject(type, objectRef.getOid(), null, result); objectRef.getValue().setObject(object); result.recordSuccess(); return object; } catch (ObjectNotFoundException ex) { result.recordFatalError("Object not found", ex); throw ex; } catch (SchemaException ex) { result.recordFatalError("Schema error", ex); throw ex; } } @Override public void setObjectTransient(PrismObject object) { if (object == null) { PrismReference objectRef = taskPrism.findReference(TaskType.F_OBJECT_REF); if (objectRef != null) { taskPrism.getValue().remove(objectRef); } } else { PrismReference objectRef; try { objectRef = taskPrism.findOrCreateReference(TaskType.F_OBJECT_REF); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } objectRef.getValue().setObject(object); } } /* * Name */ @Override public PolyStringType getName() { return taskPrism.asObjectable().getName(); } @Override public void setName(PolyStringType value) { processModificationBatched(setNameAndPrepareDelta(value)); } @Override public void setName(String value) { processModificationBatched(setNameAndPrepareDelta(new PolyStringType(value))); } @Override public void setNameImmediate(PolyStringType value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { processModificationNow(setNameAndPrepareDelta(value), parentResult); } public void setNameTransient(PolyStringType name) { taskPrism.asObjectable().setName(name); } private PropertyDelta<?> setNameAndPrepareDelta(PolyStringType value) { setNameTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_NAME, value.toPolyString()) : null; } /* * Description */ @Override public String getDescription() { return taskPrism.asObjectable().getDescription(); } @Override public void setDescription(String value) { processModificationBatched(setDescriptionAndPrepareDelta(value)); } @Override public void setDescriptionImmediate(String value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setDescriptionAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setDescriptionTransient(String name) { taskPrism.asObjectable().setDescription(name); } private PropertyDelta<?> setDescriptionAndPrepareDelta(String value) { setDescriptionTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_DESCRIPTION, value) : null; } /* * Parent */ @Override public String getParent() { return taskPrism.asObjectable().getParent(); } @Override public Task getParentTask(OperationResult result) throws SchemaException, ObjectNotFoundException { if (getParent() == null) { return null; } else { return taskManager.getTaskByIdentifier(getParent(), result); } } public void setParent(String value) { processModificationBatched(setParentAndPrepareDelta(value)); } public void setParentImmediate(String value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setParentAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setParentTransient(String name) { taskPrism.asObjectable().setParent(name); } private PropertyDelta<?> setParentAndPrepareDelta(String value) { setParentTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_PARENT, value) : null; } /* * Dependents */ @Override public List<String> getDependents() { return taskPrism.asObjectable().getDependent(); } @Override public List<Task> listDependents(OperationResult parentResult) throws SchemaException, ObjectNotFoundException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "listDependents"); result.addContext(OperationResult.CONTEXT_OID, getOid()); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); List<Task> dependents = new ArrayList<Task>(getDependents().size()); for (String dependentId : getDependents()) { try { Task dependent = taskManager.getTaskByIdentifier(dependentId, result); dependents.add(dependent); } catch (ObjectNotFoundException e) { LOGGER.trace("Dependent task {} was not found. Probably it was not yet stored to repo; we just ignore it.", dependentId); } } result.recordSuccessIfUnknown(); return dependents; } @Override public void addDependent(String value) { processModificationBatched(addDependentAndPrepareDelta(value)); } public void addDependentTransient(String name) { taskPrism.asObjectable().getDependent().add(name); } private PropertyDelta<?> addDependentAndPrepareDelta(String value) { addDependentTransient(value); return isPersistent() ? PropertyDelta.createAddDelta( taskManager.getTaskObjectDefinition(), TaskType.F_DEPENDENT, value) : null; } @Override public void deleteDependent(String value) { processModificationBatched(deleteDependentAndPrepareDelta(value)); } public void deleteDependentTransient(String name) { taskPrism.asObjectable().getDependent().remove(name); } private PropertyDelta<?> deleteDependentAndPrepareDelta(String value) { deleteDependentTransient(value); return isPersistent() ? PropertyDelta.createDeleteDelta( taskManager.getTaskObjectDefinition(), TaskType.F_DEPENDENT, value) : null; } /* * Extension */ @Override public PrismContainer<?> getExtension() { return taskPrism.getExtension(); } @Override public <T> PrismProperty<T> getExtensionProperty(QName propertyName) { if (getExtension() != null) { return getExtension().findProperty(propertyName); } else { return null; } } @Override public <T> T getExtensionPropertyRealValue(QName propertyName) { PrismProperty<T> property = getExtensionProperty(propertyName); if (property == null || property.isEmpty()) { return null; } else { return property.getRealValue(); } } @Override public Item<?,?> getExtensionItem(QName propertyName) { if (getExtension() != null) { return getExtension().findItem(propertyName); } else { return null; } } @Override public PrismReference getExtensionReference(QName propertyName) { Item item = getExtensionItem(propertyName); return (PrismReference) item; } @Override public void setExtensionItem(Item item) throws SchemaException { if (item instanceof PrismProperty) { setExtensionProperty((PrismProperty) item); } else if (item instanceof PrismReference) { setExtensionReference((PrismReference) item); } else if (item instanceof PrismContainer) { setExtensionContainer((PrismContainer) item); } else { throw new IllegalArgumentException("Unknown kind of item: " + (item == null ? "(null)" : item.getClass())); } } @Override public void setExtensionProperty(PrismProperty<?> property) throws SchemaException { processModificationBatched(setExtensionPropertyAndPrepareDelta(property.getElementName(), property.getDefinition(), PrismValue.cloneCollection(property.getValues()))); } @Override public void setExtensionReference(PrismReference reference) throws SchemaException { processModificationBatched(setExtensionReferenceAndPrepareDelta(reference.getElementName(), reference.getDefinition(), PrismValue.cloneCollection(reference.getValues()))); } @Override public void addExtensionReference(PrismReference reference) throws SchemaException { processModificationBatched(addExtensionReferenceAndPrepareDelta(reference.getElementName(), reference.getDefinition(), PrismValue.cloneCollection(reference.getValues()))); } @Override public <C extends Containerable> void setExtensionContainer(PrismContainer<C> container) throws SchemaException { processModificationBatched(setExtensionContainerAndPrepareDelta(container.getElementName(), container.getDefinition(), PrismValue.cloneCollection(container.getValues()))); } // use this method to avoid cloning the value @Override public <T> void setExtensionPropertyValue(QName propertyName, T value) throws SchemaException { PrismPropertyDefinition propertyDef = getPrismContext().getSchemaRegistry().findPropertyDefinitionByElementName(propertyName); if (propertyDef == null) { throw new SchemaException("Unknown property " + propertyName); } ArrayList<PrismPropertyValue<T>> values = new ArrayList(1); if (value != null) { values.add(new PrismPropertyValue<T>(value)); } processModificationBatched(setExtensionPropertyAndPrepareDelta(propertyName, propertyDef, values)); } @Override public <T> void setExtensionPropertyValueTransient(QName propertyName, T value) throws SchemaException { PrismPropertyDefinition propertyDef = getPrismContext().getSchemaRegistry().findPropertyDefinitionByElementName(propertyName); if (propertyDef == null) { throw new SchemaException("Unknown property " + propertyName); } ArrayList<PrismPropertyValue<T>> values = new ArrayList(1); if (value != null) { values.add(new PrismPropertyValue<T>(value)); } ItemDelta delta = new PropertyDelta(new ItemPath(TaskType.F_EXTENSION, propertyName), propertyDef, getPrismContext()); delta.setValuesToReplace(values); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(1); modifications.add(delta); PropertyDelta.applyTo(modifications, taskPrism); } // use this method to avoid cloning the value @Override public <T extends Containerable> void setExtensionContainerValue(QName containerName, T value) throws SchemaException { PrismContainerDefinition containerDef = getPrismContext().getSchemaRegistry().findContainerDefinitionByElementName(containerName); if (containerDef == null) { throw new SchemaException("Unknown container item " + containerName); } ArrayList<PrismContainerValue<T>> values = new ArrayList(1); values.add(value.asPrismContainerValue()); processModificationBatched(setExtensionContainerAndPrepareDelta(containerName, containerDef, values)); } @Override public void addExtensionProperty(PrismProperty<?> property) throws SchemaException { processModificationBatched(addExtensionPropertyAndPrepareDelta(property.getElementName(), property.getDefinition(), PrismValue.cloneCollection(property.getValues()))); } @Override public void deleteExtensionProperty(PrismProperty<?> property) throws SchemaException { processModificationBatched(deleteExtensionPropertyAndPrepareDelta(property.getElementName(), property.getDefinition(), PrismValue.cloneCollection(property.getValues()))); } @Override public void modifyExtension(ItemDelta itemDelta) throws SchemaException { if (itemDelta.getPath() == null || itemDelta.getPath().first() == null || !TaskType.F_EXTENSION.equals(ItemPath.getName(itemDelta.getPath().first()))) { throw new IllegalArgumentException("modifyExtension must modify the Task extension element; however, the path is " + itemDelta.getPath()); } processModificationBatched(modifyExtensionAndPrepareDelta(itemDelta)); } @Override public void setExtensionPropertyImmediate(PrismProperty<?> property, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setExtensionPropertyAndPrepareDelta(property.getElementName(), property.getDefinition(), PrismValue.cloneCollection(property.getValues())), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } private ItemDelta<?,?> setExtensionPropertyAndPrepareDelta(QName itemName, PrismPropertyDefinition definition, Collection<? extends PrismPropertyValue> values) throws SchemaException { ItemDelta delta = new PropertyDelta(new ItemPath(TaskType.F_EXTENSION, itemName), definition, getPrismContext()); return setExtensionItemAndPrepareDeltaCommon(delta, values); } private ItemDelta<?,?> setExtensionReferenceAndPrepareDelta(QName itemName, PrismReferenceDefinition definition, Collection<? extends PrismReferenceValue> values) throws SchemaException { ItemDelta delta = new ReferenceDelta(new ItemPath(TaskType.F_EXTENSION, itemName), definition, getPrismContext()); return setExtensionItemAndPrepareDeltaCommon(delta, values); } private ItemDelta<?,?> addExtensionReferenceAndPrepareDelta(QName itemName, PrismReferenceDefinition definition, Collection<? extends PrismReferenceValue> values) throws SchemaException { ItemDelta delta = new ReferenceDelta(new ItemPath(TaskType.F_EXTENSION, itemName), definition, getPrismContext()); return addExtensionItemAndPrepareDeltaCommon(delta, values); } private ItemDelta<?,?> setExtensionContainerAndPrepareDelta(QName itemName, PrismContainerDefinition definition, Collection<? extends PrismContainerValue> values) throws SchemaException { ItemDelta delta = new ContainerDelta(new ItemPath(TaskType.F_EXTENSION, itemName), definition, getPrismContext()); return setExtensionItemAndPrepareDeltaCommon(delta, values); } private <V extends PrismValue> ItemDelta<?,?> setExtensionItemAndPrepareDeltaCommon(ItemDelta delta, Collection<V> values) throws SchemaException { // these values should have no parent, otherwise the following will fail delta.setValuesToReplace(values); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(1); modifications.add(delta); PropertyDelta.applyTo(modifications, taskPrism); // i.e. here we apply changes only locally (in memory) return isPersistent() ? delta : null; } private <V extends PrismValue> ItemDelta<?,?> addExtensionItemAndPrepareDeltaCommon(ItemDelta delta, Collection<V> values) throws SchemaException { // these values should have no parent, otherwise the following will fail delta.addValuesToAdd(values); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(1); modifications.add(delta); PropertyDelta.applyTo(modifications, taskPrism); // i.e. here we apply changes only locally (in memory) return isPersistent() ? delta : null; } private ItemDelta<?,?> modifyExtensionAndPrepareDelta(ItemDelta<?,?> delta) throws SchemaException { Collection<ItemDelta<?,?>> modifications = new ArrayList<ItemDelta<?,?>>(1); modifications.add(delta); PropertyDelta.applyTo(modifications, taskPrism); // i.e. here we apply changes only locally (in memory) return isPersistent() ? delta : null; } private ItemDelta<?,?> addExtensionPropertyAndPrepareDelta(QName itemName, PrismPropertyDefinition definition, Collection<? extends PrismPropertyValue> values) throws SchemaException { ItemDelta delta = new PropertyDelta(new ItemPath(TaskType.F_EXTENSION, itemName), definition, getPrismContext()); delta.addValuesToAdd(values); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(1); modifications.add(delta); PropertyDelta.applyTo(modifications, taskPrism); // i.e. here we apply changes only locally (in memory) return isPersistent() ? delta : null; } private ItemDelta<?,?> deleteExtensionPropertyAndPrepareDelta(QName itemName, PrismPropertyDefinition definition, Collection<? extends PrismPropertyValue> values) throws SchemaException { ItemDelta delta = new PropertyDelta(new ItemPath(TaskType.F_EXTENSION, itemName), definition, getPrismContext()); delta.addValuesToDelete(values); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(1); modifications.add(delta); PropertyDelta.applyTo(modifications, taskPrism); // i.e. here we apply changes only locally (in memory) return isPersistent() ? delta : null; } /* * Requestee */ @Override public PrismObject<UserType> getRequestee() { return requestee; } @Override public void setRequesteeTransient(PrismObject<UserType> user) { requestee = user; } /* * Model operation context */ @Override public LensContextType getModelOperationContext() { return taskPrism.asObjectable().getModelOperationContext(); } @Override public void setModelOperationContext(LensContextType value) throws SchemaException { processModificationBatched(setModelOperationContextAndPrepareDelta(value)); } //@Override public void setModelOperationContextImmediate(LensContextType value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setModelOperationContextAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setModelOperationContextTransient(LensContextType value) { taskPrism.asObjectable().setModelOperationContext(value); } private ItemDelta<?, ?> setModelOperationContextAndPrepareDelta(LensContextType value) throws SchemaException { setModelOperationContextTransient(value); if (!isPersistent()) { return null; } if (value != null) { return DeltaBuilder.deltaFor(TaskType.class, getPrismContext()) .item(F_MODEL_OPERATION_CONTEXT).replace(value.asPrismContainerValue().clone()) .asItemDelta(); } else { return DeltaBuilder.deltaFor(TaskType.class, getPrismContext()) .item(F_MODEL_OPERATION_CONTEXT).replace() .asItemDelta(); } } /* * Workflow context */ public void setWorkflowContext(WfContextType value) throws SchemaException { processModificationBatched(setWorkflowContextAndPrepareDelta(value)); } //@Override public void setWorkflowContextImmediate(WfContextType value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setWorkflowContextAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setWorkflowContextTransient(WfContextType value) { taskPrism.asObjectable().setWorkflowContext(value); } private ItemDelta<?, ?> setWorkflowContextAndPrepareDelta(WfContextType value) throws SchemaException { setWorkflowContextTransient(value); if (!isPersistent()) { return null; } if (value != null) { return DeltaBuilder.deltaFor(TaskType.class, getPrismContext()) .item(F_WORKFLOW_CONTEXT).replace(value.asPrismContainerValue().clone()) .asItemDelta(); } else { return DeltaBuilder.deltaFor(TaskType.class, getPrismContext()) .item(F_WORKFLOW_CONTEXT).replace() .asItemDelta(); } } @Override public WfContextType getWorkflowContext() { return taskPrism.asObjectable().getWorkflowContext(); } @Override public void initializeWorkflowContextImmediate(String processInstanceId, OperationResult result) throws SchemaException, ObjectNotFoundException { WfContextType wfContextType = new WfContextType(getPrismContext()); wfContextType.setProcessInstanceId(processInstanceId); setWorkflowContextImmediate(wfContextType, result); } // @Override // public PrismReference getRequesteeRef() { // return (PrismReference) getExtensionItem(SchemaConstants.C_TASK_REQUESTEE_REF); // } // @Override // public String getRequesteeOid() { // PrismProperty<String> property = (PrismProperty<String>) getExtensionProperty(SchemaConstants.C_TASK_REQUESTEE_OID); // if (property != null) { // return property.getRealValue(); // } else { // return null; // } // } // @Override // public void setRequesteeRef(PrismReferenceValue requesteeRef) throws SchemaException { // PrismReferenceDefinition itemDefinition = new PrismReferenceDefinition(SchemaConstants.C_TASK_REQUESTEE_REF, // SchemaConstants.C_TASK_REQUESTEE_REF, ObjectReferenceType.COMPLEX_TYPE, taskManager.getPrismContext()); // itemDefinition.setTargetTypeName(UserType.COMPLEX_TYPE); // // PrismReference ref = new PrismReference(SchemaConstants.C_TASK_REQUESTEE_REF); // ref.setDefinition(itemDefinition); // ref.add(requesteeRef); // setExtensionReference(ref); // } // @Override // public void setRequesteeRef(PrismObject<UserType> requestee) throws SchemaException { // Validate.notNull(requestee.getOid()); // PrismReferenceValue value = new PrismReferenceValue(requestee.getOid()); // value.setTargetType(UserType.COMPLEX_TYPE); // setRequesteeRef(value); // } // @Override // public void setRequesteeOid(String oid) throws SchemaException { // setExtensionProperty(prepareRequesteeProperty(oid)); // } // @Override // public void setRequesteeOidImmediate(String oid, OperationResult result) throws SchemaException, ObjectNotFoundException { // setExtensionPropertyImmediate(prepareRequesteeProperty(oid), result); // } // private PrismProperty<String> prepareRequesteeProperty(String oid) { // PrismPropertyDefinition definition = taskManager.getPrismContext().getSchemaRegistry().findPropertyDefinitionByElementName(SchemaConstants.C_TASK_REQUESTEE_OID); // if (definition == null) { // throw new SystemException("No definition for " + SchemaConstants.C_TASK_REQUESTEE_OID); // } // PrismProperty<String> property = definition.instantiate(); // property.setRealValue(oid); // return property; // } /* * Node */ @Override public String getNode() { return taskPrism.asObjectable().getNode(); } public void setNode(String value) { processModificationBatched(setNodeAndPrepareDelta(value)); } public void setNodeImmediate(String value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setNodeAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setNodeTransient(String value) { taskPrism.asObjectable().setNode(value); } private PropertyDelta<?> setNodeAndPrepareDelta(String value) { setNodeTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_NODE, value) : null; } /* * Last run start timestamp */ @Override public Long getLastRunStartTimestamp() { XMLGregorianCalendar gc = taskPrism.asObjectable().getLastRunStartTimestamp(); return gc != null ? new Long(XmlTypeConverter.toMillis(gc)) : null; } public void setLastRunStartTimestamp(Long value) { processModificationBatched(setLastRunStartTimestampAndPrepareDelta(value)); } public void setLastRunStartTimestampImmediate(Long value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setLastRunStartTimestampAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setLastRunStartTimestampTransient(Long value) { taskPrism.asObjectable().setLastRunStartTimestamp( XmlTypeConverter.createXMLGregorianCalendar(value)); } private PropertyDelta<?> setLastRunStartTimestampAndPrepareDelta(Long value) { setLastRunStartTimestampTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_LAST_RUN_START_TIMESTAMP, taskPrism.asObjectable().getLastRunStartTimestamp()) : null; } /* * Last run finish timestamp */ @Override public Long getLastRunFinishTimestamp() { XMLGregorianCalendar gc = taskPrism.asObjectable().getLastRunFinishTimestamp(); return gc != null ? new Long(XmlTypeConverter.toMillis(gc)) : null; } public void setLastRunFinishTimestamp(Long value) { processModificationBatched(setLastRunFinishTimestampAndPrepareDelta(value)); } public void setLastRunFinishTimestampImmediate(Long value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setLastRunFinishTimestampAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setLastRunFinishTimestampTransient(Long value) { taskPrism.asObjectable().setLastRunFinishTimestamp( XmlTypeConverter.createXMLGregorianCalendar(value)); } private PropertyDelta<?> setLastRunFinishTimestampAndPrepareDelta(Long value) { setLastRunFinishTimestampTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_LAST_RUN_FINISH_TIMESTAMP, taskPrism.asObjectable().getLastRunFinishTimestamp()) : null; } /* * Completion timestamp */ @Override public Long getCompletionTimestamp() { XMLGregorianCalendar gc = taskPrism.asObjectable().getCompletionTimestamp(); return gc != null ? new Long(XmlTypeConverter.toMillis(gc)) : null; } public void setCompletionTimestamp(Long value) { processModificationBatched(setCompletionTimestampAndPrepareDelta(value)); } public void setCompletionTimestampImmediate(Long value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setCompletionTimestampAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setCompletionTimestampTransient(Long value) { taskPrism.asObjectable().setCompletionTimestamp( XmlTypeConverter.createXMLGregorianCalendar(value)); } private PropertyDelta<?> setCompletionTimestampAndPrepareDelta(Long value) { setCompletionTimestampTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_COMPLETION_TIMESTAMP, taskPrism.asObjectable().getCompletionTimestamp()) : null; } /* * Next run start time */ @Override public Long getNextRunStartTime(OperationResult parentResult) { return taskManager.getNextRunStartTime(getOid(), parentResult); } @Override public String debugDump() { return debugDump(0); } @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); DebugUtil.indentDebugDump(sb, indent); sb.append("Task("); sb.append(TaskQuartzImpl.class.getName()); sb.append(")\n"); sb.append(taskPrism.debugDump(indent + 1)); sb.append("\n persistenceStatus: "); sb.append(getPersistenceStatus()); sb.append("\n result: "); if (taskResult ==null) { sb.append("null"); } else { sb.append(taskResult.debugDump()); } return sb.toString(); } /* * Handler and category */ public TaskHandler getHandler() { String handlerUri = taskPrism.asObjectable().getHandlerUri(); return handlerUri != null ? taskManager.getHandler(handlerUri) : null; } @Override public void setCategory(String value) { processModificationBatched(setCategoryAndPrepareDelta(value)); } public void setCategoryImmediate(String value, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { processModificationNow(setCategoryAndPrepareDelta(value), parentResult); } catch (ObjectAlreadyExistsException ex) { throw new SystemException(ex); } } public void setCategoryTransient(String value) { try { taskPrism.setPropertyRealValue(TaskType.F_CATEGORY, value); } catch (SchemaException e) { // This should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } } private PropertyDelta<?> setCategoryAndPrepareDelta(String value) { setCategoryTransient(value); return isPersistent() ? PropertyDelta.createReplaceDeltaOrEmptyDelta( taskManager.getTaskObjectDefinition(), TaskType.F_CATEGORY, value) : null; } @Override public String getCategory() { return taskPrism.asObjectable().getCategory(); } public String getCategoryFromHandler() { TaskHandler h = getHandler(); if (h != null) { return h.getCategoryName(this); } else { return null; } } /* * Other methods */ @Override public void refresh(OperationResult parentResult) throws ObjectNotFoundException, SchemaException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE+"refresh"); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); result.addContext(OperationResult.CONTEXT_OID, getOid()); if (!isPersistent()) { // Nothing to do for transient tasks result.recordSuccess(); return; } PrismObject<TaskType> repoObj; try { repoObj = repositoryService.getObject(TaskType.class, getOid(), null, result); } catch (ObjectNotFoundException ex) { result.recordFatalError("Object not found", ex); throw ex; } catch (SchemaException ex) { result.recordFatalError("Schema error", ex); throw ex; } updateTaskInstance(repoObj, result); result.recordSuccess(); } private void updateTaskInstance(PrismObject<TaskType> taskPrism, OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "updateTaskInstance"); result.addArbitraryObjectAsParam("task", this); result.addParam("taskPrism", taskPrism); replaceTaskPrism(taskPrism); resolveOwnerRef(result); result.recordSuccessIfUnknown(); } // public void modify(Collection<? extends ItemDelta> modifications, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { // throw new UnsupportedOperationException("Generic task modification is not supported. Please use concrete setter methods to modify a task"); // PropertyDelta.applyTo(modifications, taskPrism); // if (isPersistent()) { // getRepositoryService().modifyObject(TaskType.class, getOid(), modifications, parentResult); // } // } /** * Signal the task to shut down. * It may not stop immediately, but it should stop eventually. * * BEWARE, this method has to be invoked on the same Task instance that is executing. * If called e.g. on a Task just retrieved from the repository, it will have no effect whatsoever. */ public void unsetCanRun() { // beware: Do not touch task prism here, because this method can be called asynchronously canRun = false; } @Override public boolean canRun() { return canRun; } // checks latest start time (useful for recurring tightly coupled tasks) public boolean stillCanStart() { if (getSchedule() != null && getSchedule().getLatestStartTime() != null) { long lst = getSchedule().getLatestStartTime().toGregorianCalendar().getTimeInMillis(); return lst >= System.currentTimeMillis(); } else { return true; } } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Task(id:" + getTaskIdentifier() + ", name:" + getName() + ", oid:" + getOid() + ")"; } @Override public int hashCode() { return taskPrism.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TaskQuartzImpl other = (TaskQuartzImpl) obj; // if (persistenceStatus != other.persistenceStatus) // return false; if (taskResult == null) { if (other.taskResult != null) return false; } else if (!taskResult.equals(other.taskResult)) return false; if (taskPrism == null) { if (other.taskPrism != null) return false; } else if (!taskPrism.equals(other.taskPrism)) return false; return true; } private PrismContext getPrismContext() { return taskManager.getPrismContext(); } @Override public Task createSubtask() { TaskQuartzImpl sub = (TaskQuartzImpl) taskManager.createTaskInstance(); sub.setParent(this.getTaskIdentifier()); sub.setOwner(this.getOwner()); sub.setChannel(this.getChannel()); // taskManager.registerTransientSubtask(sub, this); LOGGER.trace("New subtask {} has been created.", sub.getTaskIdentifier()); return sub; } @Override public Task createSubtask(LightweightTaskHandler handler) { TaskQuartzImpl sub = ((TaskQuartzImpl) createSubtask()); sub.setLightweightTaskHandler(handler); lightweightAsynchronousSubtasks.add(sub); return sub; } @Deprecated public TaskRunResult waitForSubtasks(Integer interval, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { return waitForSubtasks(interval, null, parentResult); } @Deprecated public TaskRunResult waitForSubtasks(Integer interval, Collection<ItemDelta<?,?>> extensionDeltas, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "waitForSubtasks"); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); result.addContext(OperationResult.CONTEXT_OID, getOid()); TaskRunResult trr = new TaskRunResult(); trr.setProgress(this.getProgress()); trr.setRunResultStatus(TaskRunResult.TaskRunResultStatus.RESTART_REQUESTED); trr.setOperationResult(null); ScheduleType schedule = new ScheduleType(); if (interval != null) { schedule.setInterval(interval); } else { schedule.setInterval(30); } pushHandlerUri(WaitForSubtasksByPollingTaskHandler.HANDLER_URI, schedule, null, extensionDeltas); setBinding(TaskBinding.LOOSE); savePendingModifications(result); return trr; } // @Override // public boolean waitForTransientSubtasks(long timeout, OperationResult parentResult) { // long endTime = System.currentTimeMillis() + timeout; // for (Task t : transientSubtasks) { // TaskQuartzImpl tqi = (TaskQuartzImpl) t; // if (!tqi.lightweightTaskHandlerFinished()) { // long wait = endTime - System.currentTimeMillis(); // if (wait <= 0) { // return false; // } // try { // tqi.threadForLightweightTaskHandler.join(wait); // } catch (InterruptedException e) { // return false; // } // if (tqi.threadForLightweightTaskHandler.isAlive()) { // return false; // } // } // } // LOGGER.trace("All transient subtasks finished for task {}", this); // return true; // } public List<PrismObject<TaskType>> listSubtasksRaw(OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "listSubtasksRaw"); result.addContext(OperationResult.CONTEXT_OID, getOid()); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); if (!isPersistent()) { result.recordSuccessIfUnknown(); return new ArrayList<>(0); } return taskManager.listSubtasksForTask(getTaskIdentifier(), result); } public List<PrismObject<TaskType>> listPrerequisiteTasksRaw(OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "listPrerequisiteTasksRaw"); result.addContext(OperationResult.CONTEXT_OID, getOid()); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); ObjectQuery query = QueryBuilder.queryFor(TaskType.class, getPrismContext()) .item(TaskType.F_DEPENDENT).eq(getTaskIdentifier()) .build(); List<PrismObject<TaskType>> list = taskManager.getRepositoryService().searchObjects(TaskType.class, query, null, result); result.recordSuccessIfUnknown(); return list; } @Override public List<Task> listSubtasks(OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "listSubtasks"); result.addContext(OperationResult.CONTEXT_OID, getOid()); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); return listSubtasksInternal(result); } private List<Task> listSubtasksInternal(OperationResult result) throws SchemaException { List<Task> retval = new ArrayList<>(); // persistent subtasks retval.addAll(taskManager.resolveTasksFromTaskTypes(listSubtasksRaw(result), result)); // transient asynchronous subtasks - must be taken from the running task instance! retval.addAll(taskManager.getTransientSubtasks(this)); return retval; } @Override public List<Task> listSubtasksDeeply(OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "listSubtasksDeeply"); result.addContext(OperationResult.CONTEXT_OID, getOid()); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); ArrayList<Task> retval = new ArrayList<Task>(); addSubtasks(retval, this, result); return retval; } private void addSubtasks(ArrayList<Task> tasks, TaskQuartzImpl taskToProcess, OperationResult result) throws SchemaException { for (Task task : taskToProcess.listSubtasksInternal(result)) { tasks.add(task); addSubtasks(tasks, (TaskQuartzImpl) task, result); } } @Override public List<Task> listPrerequisiteTasks(OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "listPrerequisiteTasks"); result.addContext(OperationResult.CONTEXT_OID, getOid()); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskQuartzImpl.class); return taskManager.resolveTasksFromTaskTypes(listPrerequisiteTasksRaw(result), result); } // private List<Task> resolveTasksFromIdentifiers(OperationResult result, List<String> identifiers) throws SchemaException { // List<Task> tasks = new ArrayList<Task>(identifiers.size()); // for (String identifier : identifiers) { // tasks.add(taskManager.getTaskByIdentifier(result)); // } // // result.recordSuccessIfUnknown(); // return tasks; // } @Override public void pushWaitForTasksHandlerUri() { pushHandlerUri(WaitForTasksTaskHandler.HANDLER_URI, new ScheduleType(), null); } public void setLightweightTaskHandler(LightweightTaskHandler lightweightTaskHandler) { this.lightweightTaskHandler = lightweightTaskHandler; } @Override public LightweightTaskHandler getLightweightTaskHandler() { return lightweightTaskHandler; } @Override public boolean isLightweightAsynchronousTask() { return lightweightTaskHandler != null; } void setLightweightHandlerFuture(Future lightweightHandlerFuture) { this.lightweightHandlerFuture = lightweightHandlerFuture; } public Future getLightweightHandlerFuture() { return lightweightHandlerFuture; } @Override public Set<? extends Task> getLightweightAsynchronousSubtasks() { return Collections.unmodifiableSet(lightweightAsynchronousSubtasks); } @Override public Set<? extends Task> getRunningLightweightAsynchronousSubtasks() { // beware: Do not touch task prism here, because this method can be called asynchronously Set<Task> retval = new HashSet<>(); for (Task subtask : getLightweightAsynchronousSubtasks()) { if (subtask.getExecutionStatus() == TaskExecutionStatus.RUNNABLE && subtask.lightweightHandlerStartRequested()) { retval.add(subtask); } } return Collections.unmodifiableSet(retval); } @Override public boolean lightweightHandlerStartRequested() { return lightweightHandlerFuture != null; } // just a shortcut @Override public void startLightweightHandler() { taskManager.startLightweightTask(this); } public void setLightweightHandlerExecuting(boolean lightweightHandlerExecuting) { this.lightweightHandlerExecuting = lightweightHandlerExecuting; } public boolean isLightweightHandlerExecuting() { return lightweightHandlerExecuting; } // Operational data private EnvironmentalPerformanceInformation getEnvironmentalPerformanceInformation() { return environmentalPerformanceInformation; } private SynchronizationInformation getSynchronizationInformation() { return synchronizationInformation; } private IterativeTaskInformation getIterativeTaskInformation() { return iterativeTaskInformation; } public ActionsExecutedInformation getActionsExecutedInformation() { return actionsExecutedInformation; } @Override public OperationStatsType getAggregatedLiveOperationStats() { EnvironmentalPerformanceInformationType env = getAggregateEnvironmentalPerformanceInformation(); IterativeTaskInformationType itit = getAggregateIterativeTaskInformation(); SynchronizationInformationType sit = getAggregateSynchronizationInformation(); ActionsExecutedInformationType aeit = getAggregateActionsExecutedInformation(); if (env == null && itit == null && sit == null && aeit == null) { return null; } OperationStatsType rv = new OperationStatsType(); rv.setEnvironmentalPerformanceInformation(env); rv.setIterativeTaskInformation(itit); rv.setSynchronizationInformation(sit); rv.setActionsExecutedInformation(aeit); rv.setTimestamp(XmlTypeConverter.createXMLGregorianCalendar(new Date())); return rv; } private EnvironmentalPerformanceInformationType getAggregateEnvironmentalPerformanceInformation() { if (environmentalPerformanceInformation == null) { return null; } EnvironmentalPerformanceInformationType rv = new EnvironmentalPerformanceInformationType(); EnvironmentalPerformanceInformation.addTo(rv, environmentalPerformanceInformation.getAggregatedValue()); for (Task subtask : getLightweightAsynchronousSubtasks()) { EnvironmentalPerformanceInformation info = ((TaskQuartzImpl) subtask).getEnvironmentalPerformanceInformation(); if (info != null) { EnvironmentalPerformanceInformation.addTo(rv, info.getAggregatedValue()); } } return rv; } private IterativeTaskInformationType getAggregateIterativeTaskInformation() { if (iterativeTaskInformation == null) { return null; } IterativeTaskInformationType rv = new IterativeTaskInformationType(); IterativeTaskInformation.addTo(rv, iterativeTaskInformation.getAggregatedValue(), false); for (Task subtask : getLightweightAsynchronousSubtasks()) { IterativeTaskInformation info = ((TaskQuartzImpl) subtask).getIterativeTaskInformation(); if (info != null) { IterativeTaskInformation.addTo(rv, info.getAggregatedValue(), false); } } return rv; } private SynchronizationInformationType getAggregateSynchronizationInformation() { if (synchronizationInformation == null) { return null; } SynchronizationInformationType rv = new SynchronizationInformationType(); SynchronizationInformation.addTo(rv, synchronizationInformation.getAggregatedValue()); for (Task subtask : getLightweightAsynchronousSubtasks()) { SynchronizationInformation info = ((TaskQuartzImpl) subtask).getSynchronizationInformation(); if (info != null) { SynchronizationInformation.addTo(rv, info.getAggregatedValue()); } } return rv; } private ActionsExecutedInformationType getAggregateActionsExecutedInformation() { if (actionsExecutedInformation == null) { return null; } ActionsExecutedInformationType rv = new ActionsExecutedInformationType(); ActionsExecutedInformation.addTo(rv, actionsExecutedInformation.getAggregatedValue()); for (Task subtask : getLightweightAsynchronousSubtasks()) { ActionsExecutedInformation info = ((TaskQuartzImpl) subtask).getActionsExecutedInformation(); if (info != null) { ActionsExecutedInformation.addTo(rv, info.getAggregatedValue()); } } return rv; } @Override public void recordState(String message) { if (LOGGER.isDebugEnabled()) { // TODO consider this LOGGER.debug("{}", message); } if (PERFORMANCE_ADVISOR.isDebugEnabled()) { PERFORMANCE_ADVISOR.debug("{}", message); } environmentalPerformanceInformation.recordState(message); } @Override public void recordProvisioningOperation(String resourceOid, String resourceName, QName objectClassName, ProvisioningOperation operation, boolean success, int count, long duration) { environmentalPerformanceInformation.recordProvisioningOperation(resourceOid, resourceName, objectClassName, operation, success, count, duration); } @Override public void recordNotificationOperation(String transportName, boolean success, long duration) { environmentalPerformanceInformation.recordNotificationOperation(transportName, success, duration); } @Override public void recordMappingOperation(String objectOid, String objectName, String objectTypeName, String mappingName, long duration) { environmentalPerformanceInformation.recordMappingOperation(objectOid, objectName, objectTypeName, mappingName, duration); } @Override public synchronized void recordSynchronizationOperationEnd(String objectName, String objectDisplayName, QName objectType, String objectOid, long started, Throwable exception, SynchronizationInformation.Record originalStateIncrement, SynchronizationInformation.Record newStateIncrement) { if (synchronizationInformation != null) { synchronizationInformation.recordSynchronizationOperationEnd(objectName, objectDisplayName, objectType, objectOid, started, exception, originalStateIncrement, newStateIncrement); } } @Override public synchronized void recordSynchronizationOperationStart(String objectName, String objectDisplayName, QName objectType, String objectOid) { if (synchronizationInformation != null) { synchronizationInformation.recordSynchronizationOperationStart(objectName, objectDisplayName, objectType, objectOid); } } @Override public synchronized void recordIterativeOperationEnd(String objectName, String objectDisplayName, QName objectType, String objectOid, long started, Throwable exception) { if (iterativeTaskInformation != null) { iterativeTaskInformation.recordOperationEnd(objectName, objectDisplayName, objectType, objectOid, started, exception); } } @Override public void recordIterativeOperationEnd(ShadowType shadow, long started, Throwable exception) { recordIterativeOperationEnd(PolyString.getOrig(shadow.getName()), StatisticsUtil.getDisplayName(shadow), ShadowType.COMPLEX_TYPE, shadow.getOid(), started, exception); } @Override public void recordIterativeOperationStart(ShadowType shadow) { recordIterativeOperationStart(PolyString.getOrig(shadow.getName()), StatisticsUtil.getDisplayName(shadow), ShadowType.COMPLEX_TYPE, shadow.getOid()); } @Override public synchronized void recordIterativeOperationStart(String objectName, String objectDisplayName, QName objectType, String objectOid) { if (iterativeTaskInformation != null) { iterativeTaskInformation.recordOperationStart(objectName, objectDisplayName, objectType, objectOid); } } @Override public void recordObjectActionExecuted(String objectName, String objectDisplayName, QName objectType, String objectOid, ChangeType changeType, String channel, Throwable exception) { if (actionsExecutedInformation != null) { actionsExecutedInformation.recordObjectActionExecuted(objectName, objectDisplayName, objectType, objectOid, changeType, channel, exception); } } @Override public void recordObjectActionExecuted(PrismObject<? extends ObjectType> object, ChangeType changeType, Throwable exception) { recordObjectActionExecuted(object, null, null, changeType, getChannel(), exception); } @Override public <T extends ObjectType> void recordObjectActionExecuted(PrismObject<T> object, Class<T> objectTypeClass, String defaultOid, ChangeType changeType, String channel, Throwable exception) { if (actionsExecutedInformation != null) { String name, displayName, oid; PrismObjectDefinition definition; Class<T> clazz; if (object != null) { name = PolyString.getOrig(object.getName()); displayName = StatisticsUtil.getDisplayName(object); definition = object.getDefinition(); clazz = object.getCompileTimeClass(); oid = object.getOid(); if (oid == null) { // in case of ADD operation oid = defaultOid; } } else { name = null; displayName = null; definition = null; clazz = objectTypeClass; oid = defaultOid; } if (definition == null && clazz != null) { definition = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(clazz); } QName typeQName; if (definition != null) { typeQName = definition.getTypeName(); } else { typeQName = ObjectType.COMPLEX_TYPE; } actionsExecutedInformation.recordObjectActionExecuted(name, displayName, typeQName, oid, changeType, channel, exception); } } @Override public void markObjectActionExecutedBoundary() { if (actionsExecutedInformation != null) { actionsExecutedInformation.markObjectActionExecutedBoundary(); } } @Override public void resetEnvironmentalPerformanceInformation(EnvironmentalPerformanceInformationType value) { environmentalPerformanceInformation = new EnvironmentalPerformanceInformation(value); } @Override public void resetSynchronizationInformation(SynchronizationInformationType value) { synchronizationInformation = new SynchronizationInformation(value); } @Override public void resetIterativeTaskInformation(IterativeTaskInformationType value) { iterativeTaskInformation = new IterativeTaskInformation(value); } @Override public void resetActionsExecutedInformation(ActionsExecutedInformationType value) { actionsExecutedInformation = new ActionsExecutedInformation(value); } @Override public void startCollectingOperationStatsFromZero(boolean enableIterationStatistics, boolean enableSynchronizationStatistics, boolean enableActionsExecutedStatistics) { resetEnvironmentalPerformanceInformation(null); if (enableIterationStatistics) { resetIterativeTaskInformation(null); } if (enableSynchronizationStatistics) { resetSynchronizationInformation(null); } if (enableActionsExecutedStatistics) { resetActionsExecutedInformation(null); } } @Override public void startCollectingOperationStatsFromStoredValues(boolean enableIterationStatistics, boolean enableSynchronizationStatistics, boolean enableActionsExecutedStatistics) { OperationStatsType stored = getStoredOperationStats(); if (stored == null) { stored = new OperationStatsType(); } resetEnvironmentalPerformanceInformation(stored.getEnvironmentalPerformanceInformation()); if (enableIterationStatistics) { resetIterativeTaskInformation(stored.getIterativeTaskInformation()); } else { iterativeTaskInformation = null; } if (enableSynchronizationStatistics) { resetSynchronizationInformation(stored.getSynchronizationInformation()); } else { synchronizationInformation = null; } if (enableActionsExecutedStatistics) { resetActionsExecutedInformation(stored.getActionsExecutedInformation()); } else { actionsExecutedInformation = null; } } @Override public void storeOperationStats() { try { setOperationStats(getAggregatedLiveOperationStats()); savePendingModifications(new OperationResult(DOT_INTERFACE + ".storeOperationStats")); // TODO fixme } catch (SchemaException|ObjectNotFoundException |ObjectAlreadyExistsException |RuntimeException e) { LoggingUtils.logUnexpectedException(LOGGER, "Couldn't store statistical information into task {}", e, this); } } }
apache-2.0
opennetworkinglab/spring-open
src/main/java/net/floodlightcontroller/threadpool/IThreadPoolService.java
512
package net.floodlightcontroller.threadpool; import java.util.concurrent.ScheduledExecutorService; import net.floodlightcontroller.core.module.IFloodlightService; public interface IThreadPoolService extends IFloodlightService { /** * Get the master scheduled thread pool executor maintained by the * ThreadPool provider. This can be used by other modules as a centralized * way to schedule tasks. * * @return */ public ScheduledExecutorService getScheduledExecutor(); }
apache-2.0
Fairly/opencor
src/plugins/miscellaneous/Core/src/busysupportwidget.cpp
4112
/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you 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. *******************************************************************************/ //============================================================================== // Busy support widget //============================================================================== #include "busysupportwidget.h" #include "busywidget.h" //============================================================================== #include <QApplication> #include <QDesktopWidget> #include <QRect> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== BusySupportWidget::BusySupportWidget() : mBusyWidget(0) { } //============================================================================== bool BusySupportWidget::isBusyWidgetVisible() const { // Return whether our busy widget is visible return mBusyWidget?mBusyWidget->isVisible():false; } //============================================================================== void BusySupportWidget::showBusyWidget(QWidget *pParent, const double &pProgress) { // Show our busy widget, which implies deleting its previous instance (if // any), creating a new one and centering it delete mBusyWidget; mBusyWidget = new BusyWidget(pParent, pProgress); centerBusyWidget(); // Make sure that our busy widget is shown straightaway // Note: indeed, depending on the operating system (e.g. OS X) and on what // we do next (e.g. retrieving a remote file), our busy widget may or // not show straightaway... QCoreApplication::sendPostedEvents(); QCoreApplication::processEvents(); } //============================================================================== void BusySupportWidget::hideBusyWidget() { // Hide our busy widget by deleting it delete mBusyWidget; mBusyWidget = 0; } //============================================================================== void BusySupportWidget::centerBusyWidget() { // Make sure that we have a busy widget if (!mBusyWidget) return; // Center our busy widget QRect desktopGeometry = qApp->desktop()->availableGeometry(); int parentWidth = mBusyWidget->parentWidget()?mBusyWidget->parentWidget()->width():desktopGeometry.width(); int parentHeight = mBusyWidget->parentWidget()?mBusyWidget->parentWidget()->height():desktopGeometry.height(); mBusyWidget->move(0.5*(parentWidth-mBusyWidget->width()), 0.5*(parentHeight-mBusyWidget->height())); } //============================================================================== void BusySupportWidget::setBusyWidgetProgress(const double &pProgress) { // Make sure that we have a busy widget if (!mBusyWidget) return; // Set the progress of our busy widget mBusyWidget->setProgress(pProgress); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //==============================================================================
apache-2.0
0x0mar/arachni
spec/arachni/component/manager_spec.rb
17896
require 'spec_helper' describe Arachni::Component::Manager do before( :all ) do @opts = Arachni::Options.instance @lib = @opts.dir['plugins'] @namespace = Arachni::Plugins @components = Arachni::Component::Manager.new( @lib, @namespace ) end after( :each ) { @components.clear } describe '#lib' do it 'returns the component library' do @components.lib.should == @lib end end describe '#namespace' do it 'returns the namespace under which all components are defined' do @components.namespace.should == @namespace end end describe '#available' do it 'returns all available components' do @components.available.sort.should == %w(wait bad distributable loop default with_options spider_hook).sort end end describe '#load_all' do it 'loads all components' do @components.load_all @components.loaded.sort.should == @components.available.sort end end describe '#load' do context 'when passed a' do context String do it 'loads the component by name' do @components.load( 'wait' ) @components.loaded.should == %w(wait) end end context Symbol do it 'loads the component by name' do @components.load( :wait ) @components.loaded.should == %w(wait) end end context Array do it 'loads the components by name' do @components.load( %w(bad distributable) ) @components.loaded.sort.should == %w(bad distributable).sort end end context 'vararg' do context String do it 'loads components by name' do @components.load( 'wait', 'bad' ) @components.loaded.sort.should == %w(bad wait).sort end end context Symbol do it 'loads components by name' do @components.load :wait, :distributable @components.loaded.sort.should == %w(wait distributable).sort end end context Array do it 'loads components by name' do @components.load( :wait, %w(bad distributable) ) @components.loaded.sort.should == %w(bad distributable wait).sort end end end context 'wildcard (*)' do context 'alone' do it 'loads all components' do @components.load( '*' ) @components.loaded.sort.should == @components.available.sort end end context 'with a category name' do it 'loads all of its components' do @components.load( 'plugins/*' ) @components.loaded.sort.should == @components.available.sort end end end context 'exclusion filter (-)' do context 'alone' do it 'loads nothing' do @components.load( '-' ) @components.loaded.sort.should be_empty end end context 'with a name' do it 'ignore that component' do @components.load( %w(* -wait) ) loaded = @components.available loaded.delete( 'wait' ) @components.loaded.sort.should == loaded.sort end end context 'with a partial name and a wildcard' do it 'ignore matching component names' do @components.load( %w(* -wai* -dist*) ) loaded = @components.available loaded.delete( 'wait' ) loaded.delete( 'distributable' ) @components.loaded.sort.should == loaded.sort end end end end context 'when a component is not found' do it 'raises Arachni::Component::Error::NotFound' do trigger = proc { @components.load :houa } expect { trigger.call }.to raise_error Arachni::Error expect { trigger.call }.to raise_error Arachni::Component::Error expect { trigger.call }.to raise_error Arachni::Component::Error::NotFound end end end describe '#load_by_tags' do context 'when passed' do context 'nil' do it 'returns an empty array' do @components.empty?.should be_true @components.load_by_tags( nil ).should == [] end end context '[]' do it 'returns an empty array' do @components.empty?.should be_true @components.load_by_tags( [] ).should == [] end end context String do it 'loads components whose tags include the given tag (as either a String or a Symbol)' do @components.empty?.should be_true @components.load_by_tags( 'wait_string' ).should == %w(wait) @components.delete( 'wait' ) @components.empty?.should be_true @components.load_by_tags( 'wait_sym' ).should == %w(wait) @components.delete( 'wait' ) @components.empty?.should be_true @components.load_by_tags( 'distributable_string' ).should == %w(distributable) @components.delete( 'distributable' ) @components.empty?.should be_true @components.load_by_tags( 'distributable_sym' ).should == %w(distributable) @components.delete( 'distributable' ) @components.empty?.should be_true end end context Symbol do it 'loads components whose tags include the given tag (as either a String or a Symbol)' do @components.empty?.should be_true @components.load_by_tags( :wait_string ).should == %w(wait) @components.delete( 'wait' ) @components.empty?.should be_true @components.load_by_tags( :wait_sym ).should == %w(wait) @components.delete( 'wait' ) @components.empty?.should be_true @components.load_by_tags( :distributable_string ).should == %w(distributable) @components.delete( 'distributable' ) @components.empty?.should be_true @components.load_by_tags( :distributable_sym ).should == %w(distributable) @components.delete( 'distributable' ) @components.empty?.should be_true end end context Array do it 'loads components which include any of the given tags (as either Strings or a Symbols)' do @components.empty?.should be_true expected = %w(wait distributable).sort @components.load_by_tags( [ :wait_string, 'distributable_string' ] ).sort.should == expected @components.clear @components.empty?.should be_true @components.load_by_tags( [ 'wait_string', :distributable_string ] ).sort.should == expected @components.clear @components.empty?.should be_true @components.load_by_tags( [ 'wait_sym', :distributable_sym ] ).sort.should == expected @components.clear @components.empty?.should be_true end end end end describe '#parse' do context 'when passed a' do context String do it 'returns an array including the component\'s name' do @components.parse( 'wait' ).should == %w(wait) end end context Symbol do it 'returns an array including the component\'s name' do @components.parse( :wait ).should == %w(wait) end end context Array do it 'loads the component by name' do @components.parse( %w(bad distributable) ).sort.should == %w(bad distributable).sort end end context 'wildcard (*)' do context 'alone' do it 'returns all components' do @components.parse( '*' ).sort.should == @components.available.sort end end context 'with a category name' do it 'returns all of its components' do @components.parse( 'plugins/*' ).sort.should == @components.available.sort end end end context 'exclusion filter (-)' do context 'alone' do it 'returns nothing' do @components.parse( '-' ).sort.should be_empty end end context 'with a name' do it 'ignores that component' do @components.parse( %w(* -wait) ) loaded = @components.available loaded.delete( 'wait' ) loaded.sort.should == loaded.sort end end context 'with a partial name and a wildcard' do it 'ignore matching component names' do parsed = @components.parse( %w(* -wai* -dist*) ) loaded = @components.available loaded.delete( 'wait' ) loaded.delete( 'distributable' ) parsed.sort.should == loaded.sort end end end end end describe '#prep_opts' do it 'prepares options for passing to the component' do c = 'with_options' @components.load( c ) @components.prep_opts( c, @components[c], { 'req_opt' => 'my value'} ).should == { "req_opt" => "my value", "opt_opt" => nil, "default_opt" => "value" } opts = { 'req_opt' => 'req_opt value', 'opt_opt' => 'opt_opt value', "default_opt" => "default_opt value" } @components.prep_opts( c, @components[c], opts ).should == opts end context 'with invalid options' do it 'raises Arachni::Component::Options::Error::Invalid' do trigger = proc do begin c = 'with_options' @components.load( c ) @components.prep_opts( c, @components[c], {} ) ensure @components.clear end end expect { trigger.call }.to raise_error Arachni::Error expect { trigger.call }.to raise_error Arachni::Component::Error expect { trigger.call }.to raise_error Arachni::Component::Options::Error expect { trigger.call }.to raise_error Arachni::Component::Options::Error::Invalid end end end describe '#[]' do context 'when passed a' do context String do it 'should load and return the component' do @components.loaded.should be_empty @components['wait'].name.should == 'Arachni::Plugins::Wait' @components.loaded.should == %w(wait) end end context Symbol do it 'should load and return the component' do @components.loaded.should be_empty @components[:wait].name.should == 'Arachni::Plugins::Wait' @components.loaded.should == %w(wait) end end end end describe '#include?' do context 'when passed a' do context String do context 'when the component has been loaded' do it 'returns true' do @components.loaded.should be_empty @components['wait'].name.should == 'Arachni::Plugins::Wait' @components.loaded.should == %w(wait) @components.loaded?( 'wait' ).should be_true @components.include?( 'wait' ).should be_true end end context 'when the component has not been loaded' do it 'returns false' do @components.loaded.should be_empty @components.loaded?( 'wait' ).should be_false @components.include?( 'wait' ).should be_false end end end context Symbol do context 'when the component has been loaded' do it 'returns true' do @components.loaded.should be_empty @components[:wait].name.should == 'Arachni::Plugins::Wait' @components.loaded.should == %w(wait) @components.loaded?( :wait ).should be_true @components.include?( :wait ).should be_true end end context 'when the component has not been loaded' do it 'returns false' do @components.loaded.should be_empty @components.loaded?( :wait ).should be_false @components.include?( :wait ).should be_false end end end end end describe '#delete' do it 'removes a component' do @components.loaded.should be_empty @components.load( 'wait' ) klass = @components['wait'] sym = klass.name.split( ':' ).last.to_sym @components.namespace.constants.include?( sym ).should be_true @components.loaded.should be_any @components.delete( 'wait' ) @components.loaded.should be_empty sym = klass.name.split( ':' ).last.to_sym @components.namespace.constants.include?( sym ).should be_false end it 'unloads a component' do @components.loaded.should be_empty @components.load( 'wait' ) klass = @components['wait'] sym = klass.name.split( ':' ).last.to_sym @components.namespace.constants.include?( sym ).should be_true @components.loaded.should be_any @components.delete( 'wait' ) @components.loaded.should be_empty sym = klass.name.split( ':' ).last.to_sym @components.namespace.constants.include?( sym ).should be_false end end describe '#available' do it 'returns all available components' do @components.available.sort.should == %w(wait bad with_options distributable loop default spider_hook).sort end end describe '#loaded' do it 'returns all loaded components' do @components.load( '*' ) @components.loaded.sort.should == %w(wait bad with_options distributable loop default spider_hook).sort end end describe '#name_to_path' do it 'returns a component\'s path from its name' do path = @components.name_to_path( 'wait' ) File.exists?( path ).should be_true File.basename( path ).should == 'wait.rb' end end describe '#path_to_name' do it 'returns a component\'s name from its path' do path = @components.name_to_path( 'wait' ) @components.path_to_name( path ).should == 'wait' end end describe '#paths' do it 'returns all component paths' do paths = @components.paths paths.each { |p| File.exists?( p ).should be_true } paths.size.should == @components.available.size end end describe '#clear' do it 'unloads all components' do @components.loaded.should be_empty @components.load( '*' ) @components.loaded.sort.should == @components.available.sort symbols = @components.values.map do |klass| sym = klass.name.split( ':' ).last.to_sym @components.namespace.constants.include?( sym ).should be_true sym end @components.clear symbols.each do |sym| @components.namespace.constants.include?( sym ).should be_false end @components.loaded.should be_empty end end end
apache-2.0
schmittjoh/php-stubs
res/php/idn/functions/idn-to-ascii.php
259
<?php /** * Convert UTF-8 encoded domain name to ASCII * * @phpstub * * @param string $utf8_domain * @param int $errorcode * * @return string The ACE encoded version of the domain name . */ function idn_to_ascii($utf8_domain, &$errorcode = NULL) { }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/constants/float64/pi/examples/index.js
709
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; var PI = require( './../lib' ); console.log( PI ); // => 3.141592653589793
apache-2.0
JLUIT/ITJob
src/com/job/activity/CollegeChooseActivity.java
4258
package com.job.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import com.job.R; import com.job.activity.JobNameActivity.SubmitThread; import com.job.base.BaseActivity; public class CollegeChooseActivity extends BaseActivity { private EditText edit; private TextView save; private String University; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.college_choose); edit = (EditText) findViewById(R.id.edit_school); save=(TextView)findViewById(R.id.save); save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub saveUniversity(); } }); } protected void saveUniversity() { Intent intent=getIntent(); String oldUniversity=intent.getStringExtra("university"); University=edit.getText().toString().trim(); Message msg = handler.obtainMessage(); if(University.equals(oldUniversity)) { msg.what=5; handler.sendMessage(msg); } else { Thread submit=new Thread(new SubmitThread()); submit.start(); } } Handler handler = new Handler() { public void handleMessage(Message msg) { switch(msg.what) { case 0: Toast.makeText(getApplicationContext(), "网络错误", Toast.LENGTH_SHORT).show(); break; case 4: Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show(); intent2Activity(PersonMessageActivity.class); break; case 5: Toast.makeText(getApplicationContext(), "与原来信息相同", Toast.LENGTH_SHORT).show(); break; case 6: Toast.makeText(getApplicationContext(), "修改失败", Toast.LENGTH_SHORT).show(); } } }; class SubmitThread implements Runnable { Message msg = handler.obtainMessage(); @Override public void run() { // TODO Auto-generated method stub JSONObject object=new JSONObject(); try { object.put("type", false);//非密码修改 object.put("P_E", "P");//个人 object.put("which", "university");//修改电话 object.put("name", LoginActivity.name); object.put("university", University); msg.what=Server(object); handler.sendMessage(msg); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public int Server(JSONObject object) { String path=LoginActivity.URL+"SetInfoManager"; try{ URL url=new URL(path); String content = String.valueOf(object); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Fiddler"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream os = conn.getOutputStream(); os.write(content.getBytes()); os.close(); int code = conn.getResponseCode(); if(code == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String result=""; result = in.readLine(); in.close(); return Integer.parseInt(result); } else return 0; }catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } }
apache-2.0
cping/LGame
Java/Loon-Lite(PureJava)/Loon-Lite-Core/src/loon/EmptyGame.java
3854
/** * Copyright 2008 - 2015 The Loon Game Engine Authors * * 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. * * @project loon * @author cping * @email:javachenpeng@yahoo.com * @version 0.5 */ package loon; import loon.canvas.Canvas; import loon.event.InputMake; import loon.event.InputMakeImpl; import loon.opengl.Mesh; import loon.utils.ObjectMap; import loon.utils.TimeUtils; import loon.utils.reply.Act; public class EmptyGame extends LGame { public EmptyGame(LSetting config, Platform plat) { super(config, plat); } // 为了方便直接转码到C#和C++,无法使用匿名内部类(也就是在构造内直接构造实现的方式),只能都写出类来. // PS:别提delegate,委托那玩意写出来太不优雅了,而且大多数J2C#的工具也不能直接转换过去…… private static class SaveEmpty implements Save { private final ObjectMap<String, String> _data = new ObjectMap<String, String>(); @Override public void setItem(String key, String data) throws RuntimeException { _data.put(key, data); } @Override public void removeItem(String key) { _data.remove(key); } @Override public String getItem(String key) { return _data.get(key); } @Override public Batch startBatch() { return new SaveBatchImpl(this); } @Override public Iterable<String> keys() { return _data.keys(); } @Override public boolean isPersisted() { return true; } } private Save save = new SaveEmpty(); private InputMake input = new InputMakeImpl(); private static class LogEmpty extends Log { @Override public void onError(Throwable e) { } @Override protected void callNativeLog(Level level, String msg, Throwable e) { System.err.println(level.levelString + msg); if (e != null) { e.printStackTrace(System.err); } } } private Log log = new LogEmpty(); private static class AsynEmpty extends Asyn.Default { public AsynEmpty(Log log, Act<? extends Object> frame) { super(log, frame); } @Override public void invokeLater(Runnable action) { action.run(); } } private Asyn exec = new AsynEmpty(log, frame); @Override public Support support() { throw new UnsupportedOperationException(); } private final long start = TimeUtils.millis(); @Override public LGame.Type type() { return LGame.Type.STUB; } @Override public double time() { return (double) TimeUtils.millis(); } @Override public int tick() { return (int) (TimeUtils.millis() - start); } @Override public void openURL(String url) { throw new UnsupportedOperationException(); } @Override public Assets assets() { throw new UnsupportedOperationException(); } @Override public Graphics graphics() { throw new UnsupportedOperationException(); } @Override public Asyn asyn() { return exec; } @Override public InputMake input() { return input; } @Override public Log log() { return log; } @Override public Save save() { return save; } Accelerometer accelerometer = new AccelerometerDefault(); @Override public Accelerometer accel() { return accelerometer; } @Override public boolean isMobile() { return false; } @Override public boolean isDesktop() { return false; } @Override public Mesh makeMesh(Canvas canvas) { throw new UnsupportedOperationException(); } }
apache-2.0
brendandouglas/intellij
java/src/com/google/idea/blaze/java/wizard2/BlazeProjectImportBuilder.java
2678
/* * Copyright 2016 The Bazel Authors. All rights reserved. * * 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 com.google.idea.blaze.java.wizard2; import com.google.common.collect.ImmutableList; import com.google.idea.blaze.base.settings.Blaze; import com.google.idea.blaze.base.wizard2.BlazeNewProjectBuilder; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.openapi.module.ModifiableModuleModel; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.SdkTypeId; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.packaging.artifacts.ModifiableArtifactModel; import com.intellij.projectImport.ProjectImportBuilder; import icons.BlazeIcons; import java.util.List; import javax.swing.Icon; import org.jetbrains.annotations.NotNull; /** Wrapper around a {@link BlazeNewProjectBuilder} to fit into IntelliJ's import framework. */ class BlazeProjectImportBuilder extends ProjectImportBuilder<Void> { private BlazeNewProjectBuilder builder = new BlazeNewProjectBuilder(); @NotNull @Override public String getName() { return Blaze.defaultBuildSystemName(); } @Override public Icon getIcon() { return BlazeIcons.Blaze; } @Override public boolean isSuitableSdkType(SdkTypeId sdk) { return sdk == JavaSdk.getInstance(); } @Override public List<Void> getList() { return ImmutableList.of(); } @Override public boolean isMarked(Void element) { return true; } @Override public void setList(List<Void> gradleProjects) {} @Override public void setOpenProjectSettingsAfter(boolean on) {} @Override public List<Module> commit( final Project project, ModifiableModuleModel model, ModulesProvider modulesProvider, ModifiableArtifactModel artifactModel) { builder.commitToProject(project); CompilerWorkspaceConfiguration.getInstance(project).MAKE_PROJECT_ON_SAVE = false; return ImmutableList.of(); } public BlazeNewProjectBuilder builder() { return builder; } }
apache-2.0
openstack-atlas/atlas-lb
core-persistence/src/test/java/org/openstack/atlas/service/domain/service/VirtualIpServiceITest.java
1972
package org.openstack.atlas.service.domain.service; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.openstack.atlas.datamodel.CoreLoadBalancerStatus; import org.openstack.atlas.service.domain.entity.LoadBalancer; import org.openstack.atlas.service.domain.exception.EntityNotFoundException; import org.openstack.atlas.service.domain.exception.PersistenceServiceException; import org.openstack.atlas.service.domain.repository.VirtualIpRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(Enclosed.class) public class VirtualIpServiceITest { @RunWith(SpringJUnit4ClassRunner.class) public static class WhenRemovingAllVipsFromALoadBalancer extends Base { @Autowired private VirtualIpService virtualIpService; @Autowired private VirtualIpRepository virtualIpRepository; @Before public void setUp() throws PersistenceServiceException { loadBalancer = loadBalancerService.create(loadBalancer); loadBalancer = loadBalancerRepository.changeStatus(loadBalancer, CoreLoadBalancerStatus.ACTIVE); } @Test public void shouldRemoveAllVips() throws EntityNotFoundException { LoadBalancer savedLb = loadBalancerRepository.getByIdAndAccountId(loadBalancer.getId(), loadBalancer.getAccountId()); Assert.assertTrue(!savedLb.getLoadBalancerJoinVipSet().isEmpty() || !savedLb.getLoadBalancerJoinVipSet().isEmpty()); virtualIpService.removeAllVipsFromLoadBalancer(savedLb); savedLb = loadBalancerRepository.getById(savedLb.getId()); Assert.assertTrue(savedLb.getLoadBalancerJoinVipSet().isEmpty() && savedLb.getLoadBalancerJoinVipSet().isEmpty()); } } }
apache-2.0
McLeodMoores/starling
projects/financial/src/main/java/com/opengamma/financial/property/UnitProperties.java
947
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.property; import com.opengamma.engine.value.ValuePropertyNames; /** * Defines property names that correspond to "units" of the value they are describing. Some operations may only be valid if the units of the operands match or * are otherwise compatible. */ public final class UnitProperties { /** * Prevents instantiation. */ private UnitProperties() { } // Standard unit names from ValuePropertyNames //CSOFF public static final String CURRENCY = ValuePropertyNames.CURRENCY; // OpenGamma specific unit names // TODO: ... //CSON /** * Returns all property names that correspond to units. * * @return an array of all property names */ public static String[] unitPropertyNames() { return new String[] {CURRENCY }; } }
apache-2.0
ox-it/talks.ox
talks/old_talks/views.py
1211
from __future__ import absolute_import import logging import requests from django.conf import settings from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect, Http404 from django.shortcuts import render from talks.old_talks.models import OldTalk, OldSeries from talks.events.models import Event, EventGroup logger = logging.getLogger(__name__) def old_talks_mappings(request, index_id): eventList = OldTalk.objects.filter(old_talk_id=index_id).values_list('event', flat=True) if len(eventList): event = Event.objects.get(id=eventList[0]); return HttpResponsePermanentRedirect(reverse('show-event', args=[event.slug])) else: return render(request, "old_talks/not_found.html") def old_series_mappings(request, index_id): # Try series eventGroupList = OldSeries.objects.filter(old_series_id=index_id).values_list('group', flat=True) if len(eventGroupList): eventGroup = EventGroup.objects.get(id=eventGroupList[0]); return HttpResponsePermanentRedirect(reverse('show-event-group', args=[eventGroup.slug])) else: return render(request, "old_talks/not_found.html")
apache-2.0
jenniferzheng/gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/test/java/org/apache/gobblin/service/FlowConfigTest.java
11995
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.gobblin.service; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.util.Map; import org.apache.commons.io.FileUtils; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.Files; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.name.Names; import com.linkedin.data.template.StringMap; import com.linkedin.restli.client.RestLiResponseException; import com.linkedin.restli.common.HttpStatus; import com.linkedin.restli.server.resources.BaseResource; import com.typesafe.config.Config; import org.apache.gobblin.config.ConfigBuilder; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.restli.EmbeddedRestliServer; import org.apache.gobblin.runtime.spec_catalog.FlowCatalog; @Test(groups = { "gobblin.service" }) public class FlowConfigTest { private FlowConfigClient _client; private EmbeddedRestliServer _server; private File _testDirectory; private static final String TEST_SPEC_STORE_DIR = "/tmp/flowConfigTest/"; private static final String TEST_GROUP_NAME = "testGroup1"; private static final String TEST_FLOW_NAME = "testFlow1"; private static final String TEST_SCHEDULE = "0 1/0 * ? * *"; private static final String TEST_TEMPLATE_URI = "FS:///templates/test.template"; private static final String TEST_DUMMY_GROUP_NAME = "dummyGroup"; private static final String TEST_DUMMY_FLOW_NAME = "dummyFlow"; @BeforeClass public void setUp() throws Exception { ConfigBuilder configBuilder = ConfigBuilder.create(); _testDirectory = Files.createTempDir(); configBuilder .addPrimitive(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY, _testDirectory.getAbsolutePath()) .addPrimitive(ConfigurationKeys.SPECSTORE_FS_DIR_KEY, TEST_SPEC_STORE_DIR); cleanUpDir(TEST_SPEC_STORE_DIR); Config config = configBuilder.build(); final FlowCatalog flowCatalog = new FlowCatalog(config); flowCatalog.startAsync(); flowCatalog.awaitRunning(); Injector injector = Guice.createInjector(new Module() { @Override public void configure(Binder binder) { binder.bind(FlowCatalog.class).annotatedWith(Names.named("flowCatalog")).toInstance(flowCatalog); // indicate that we are in unit testing since the resource is being blocked until flow catalog changes have // been made binder.bindConstant().annotatedWith(Names.named("readyToUse")).to(Boolean.TRUE); } }); _server = EmbeddedRestliServer.builder().resources( Lists.<Class<? extends BaseResource>>newArrayList(FlowConfigsResource.class)).injector(injector).build(); _server.startAsync(); _server.awaitRunning(); _client = new FlowConfigClient(String.format("http://localhost:%s/", _server.getPort())); } private void cleanUpDir(String dir) throws Exception { File specStoreDir = new File(dir); if (specStoreDir.exists()) { FileUtils.deleteDirectory(specStoreDir); } } @Test public void testCreateBadSchedule() throws Exception { Map<String, String> flowProperties = Maps.newHashMap(); flowProperties.put("param1", "value1"); FlowConfig flowConfig = new FlowConfig().setId(new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME)) .setTemplateUris(TEST_TEMPLATE_URI).setSchedule(new Schedule().setCronSchedule("bad schedule"). setRunImmediately(true)) .setProperties(new StringMap(flowProperties)); try { _client.createFlowConfig(flowConfig); } catch (RestLiResponseException e) { Assert.assertEquals(e.getStatus(), HttpStatus.S_422_UNPROCESSABLE_ENTITY.getCode()); return; } Assert.fail("Get should have gotten a 422 error"); } @Test public void testCreateBadTemplateUri() throws Exception { Map<String, String> flowProperties = Maps.newHashMap(); flowProperties.put("param1", "value1"); FlowConfig flowConfig = new FlowConfig().setId(new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME)) .setTemplateUris("FILE://bad/uri").setSchedule(new Schedule().setCronSchedule(TEST_SCHEDULE). setRunImmediately(true)) .setProperties(new StringMap(flowProperties)); try { _client.createFlowConfig(flowConfig); } catch (RestLiResponseException e) { Assert.assertEquals(e.getStatus(), HttpStatus.S_422_UNPROCESSABLE_ENTITY.getCode()); return; } Assert.fail("Get should have gotten a 422 error"); } @Test public void testCreate() throws Exception { Map<String, String> flowProperties = Maps.newHashMap(); flowProperties.put("param1", "value1"); FlowConfig flowConfig = new FlowConfig().setId(new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME)) .setTemplateUris(TEST_TEMPLATE_URI).setSchedule(new Schedule().setCronSchedule(TEST_SCHEDULE). setRunImmediately(true)) .setProperties(new StringMap(flowProperties)); _client.createFlowConfig(flowConfig); } @Test (dependsOnMethods = "testCreate") public void testCreateAgain() throws Exception { Map<String, String> flowProperties = Maps.newHashMap(); flowProperties.put("param1", "value1"); FlowConfig flowConfig = new FlowConfig().setId(new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME)) .setTemplateUris(TEST_TEMPLATE_URI).setSchedule(new Schedule().setCronSchedule(TEST_SCHEDULE)) .setProperties(new StringMap(flowProperties)); try { _client.createFlowConfig(flowConfig); } catch (RestLiResponseException e) { Assert.assertEquals(e.getStatus(), HttpStatus.S_409_CONFLICT.getCode()); return; } Assert.fail("Get should have gotten a 409 error"); } @Test (dependsOnMethods = "testCreateAgain") public void testGet() throws Exception { FlowId flowId = new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME); FlowConfig flowConfig = _client.getFlowConfig(flowId); Assert.assertEquals(flowConfig.getId().getFlowGroup(), TEST_GROUP_NAME); Assert.assertEquals(flowConfig.getId().getFlowName(), TEST_FLOW_NAME); Assert.assertEquals(flowConfig.getSchedule().getCronSchedule(), TEST_SCHEDULE ); Assert.assertEquals(flowConfig.getTemplateUris(), TEST_TEMPLATE_URI); Assert.assertTrue(flowConfig.getSchedule().isRunImmediately()); // Add this asssert back when getFlowSpec() is changed to return the raw flow spec //Assert.assertEquals(flowConfig.getProperties().size(), 1); Assert.assertEquals(flowConfig.getProperties().get("param1"), "value1"); } @Test (dependsOnMethods = "testGet") public void testUpdate() throws Exception { FlowId flowId = new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME); Map<String, String> flowProperties = Maps.newHashMap(); flowProperties.put("param1", "value1b"); flowProperties.put("param2", "value2b"); FlowConfig flowConfig = new FlowConfig().setId(new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME)) .setTemplateUris(TEST_TEMPLATE_URI).setSchedule(new Schedule().setCronSchedule(TEST_SCHEDULE)) .setProperties(new StringMap(flowProperties)); _client.updateFlowConfig(flowConfig); FlowConfig retrievedFlowConfig = _client.getFlowConfig(flowId); Assert.assertEquals(retrievedFlowConfig.getId().getFlowGroup(), TEST_GROUP_NAME); Assert.assertEquals(retrievedFlowConfig.getId().getFlowName(), TEST_FLOW_NAME); Assert.assertEquals(retrievedFlowConfig.getSchedule().getCronSchedule(), TEST_SCHEDULE ); Assert.assertEquals(retrievedFlowConfig.getTemplateUris(), TEST_TEMPLATE_URI); // Add this asssert when getFlowSpec() is changed to return the raw flow spec //Assert.assertEquals(flowConfig.getProperties().size(), 2); Assert.assertEquals(retrievedFlowConfig.getProperties().get("param1"), "value1b"); Assert.assertEquals(retrievedFlowConfig.getProperties().get("param2"), "value2b"); } @Test (dependsOnMethods = "testUpdate") public void testDelete() throws Exception { FlowId flowId = new FlowId().setFlowGroup(TEST_GROUP_NAME).setFlowName(TEST_FLOW_NAME); // make sure flow config exists FlowConfig flowConfig = _client.getFlowConfig(flowId); Assert.assertEquals(flowConfig.getId().getFlowGroup(), TEST_GROUP_NAME); Assert.assertEquals(flowConfig.getId().getFlowName(), TEST_FLOW_NAME); _client.deleteFlowConfig(flowId); try { _client.getFlowConfig(flowId); } catch (RestLiResponseException e) { Assert.assertEquals(e.getStatus(), HttpStatus.S_404_NOT_FOUND.getCode()); return; } Assert.fail("Get should have gotten a 404 error"); } @Test public void testBadGet() throws Exception { FlowId flowId = new FlowId().setFlowGroup(TEST_DUMMY_GROUP_NAME).setFlowName(TEST_DUMMY_FLOW_NAME); try { _client.getFlowConfig(flowId); } catch (RestLiResponseException e) { Assert.assertEquals(e.getStatus(), HttpStatus.S_404_NOT_FOUND.getCode()); return; } Assert.fail("Get should have raised a 404 error"); } @Test public void testBadDelete() throws Exception { FlowId flowId = new FlowId().setFlowGroup(TEST_DUMMY_GROUP_NAME).setFlowName(TEST_DUMMY_FLOW_NAME); try { _client.getFlowConfig(flowId); } catch (RestLiResponseException e) { Assert.assertEquals(e.getStatus(), HttpStatus.S_404_NOT_FOUND.getCode()); return; } Assert.fail("Get should have raised a 404 error"); } @Test public void testBadUpdate() throws Exception { Map<String, String> flowProperties = Maps.newHashMap(); flowProperties.put("param1", "value1b"); flowProperties.put("param2", "value2b"); FlowConfig flowConfig = new FlowConfig().setId(new FlowId().setFlowGroup(TEST_DUMMY_GROUP_NAME) .setFlowName(TEST_DUMMY_FLOW_NAME)) .setTemplateUris(TEST_TEMPLATE_URI).setSchedule(new Schedule().setCronSchedule(TEST_SCHEDULE)) .setProperties(new StringMap(flowProperties)); try { _client.updateFlowConfig(flowConfig); } catch (RestLiResponseException e) { Assert.assertEquals(e.getStatus(), HttpStatus.S_404_NOT_FOUND.getCode()); return; } Assert.fail("Get should have raised a 404 error"); } @AfterClass(alwaysRun = true) public void tearDown() throws Exception { if (_client != null) { _client.close(); } if (_server != null) { _server.stopAsync(); _server.awaitTerminated(); } _testDirectory.delete(); cleanUpDir(TEST_SPEC_STORE_DIR); } private static int chooseRandomPort() throws IOException { ServerSocket socket = null; try { socket = new ServerSocket(0); return socket.getLocalPort(); } finally { if (socket != null) { socket.close(); } } } }
apache-2.0
jefking/King.Route
King.Route/RouteAliasAttribute.cs
1078
namespace King.Route { using System; /// <summary> /// Attribute based routing /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class RouteAliasAttribute : Attribute { #region Members /// <summary> /// Route Name /// </summary> protected readonly string name; #endregion #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="name">Route Name</param> public RouteAliasAttribute(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("name"); } this.name = name; } #endregion #region Properties /// <summary> /// Route Name /// </summary> public virtual string Name { get { return this.name; } } #endregion } }
apache-2.0
forcedotcom/aura
aura-impl/src/main/resources/aura/attribute/AttributeSet.js
18061
/* * Copyright (C) 2013 salesforce.com, inc. * * 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. */ /** * @description Creates an AttributeSet instance. * @param {Object} * config Sets the values with the config object, if provided. * @param {Object} * valueProvider Sets the value provider for the attributes. * @param {AttributeDefSet} * attributeDefSet The metadata describing the attributes in the set. * @constructor * @protected */ function AttributeSet(attributeDefSet) { this.values = {}; this.shadowValues={}; this.decorators={}; this.attributeDefSet = attributeDefSet; this.destroyed=false; //this.initialize(attributes); // #if {"excludeModes" : ["PRODUCTION", "PRODUCTIONDEBUG", "PERFORMANCEDEBUG"]} this["values"] = this.values; // #end } /** * Whether attribute exists * * @param {String} * name - name of attribute * @returns {boolean} true if attribute exists * @private */ AttributeSet.prototype.hasAttribute = function(name) { return this.values.hasOwnProperty(name); }; /** * Returns the highest extended reference of the attribute using property syntax. * * @param {String} key The data key to look up. * @param {Object} component The component hierarchy to investigate * @returns {Object} the attribute def * @protected * */ AttributeSet.getDef = function(key, component) { var def=[]; var target=component.getConcreteComponent?component.getConcreteComponent():component; while(target){ var tempDef=target.getDef?target.getDef().getAttributeDefs().getDef(key):target.getAttributeDefs().getDef(key); if(!tempDef){ break; } def[0]=tempDef; def[1]=target; target=target.getSuper?target.getSuper():target.getSuperDef(); } return def; }; /** * Returns the value referenced using property syntax. * * @param {String} * key The data key to look up. * @returns {Object} the value of the attribute * @protected * */ AttributeSet.prototype.get = function(key, component) { var value = undefined; var path = null; var attribute=key; if (key.lastIndexOf("body", 0) === 0) { key=key.replace(/^body\b/g,"body."+component.globalId); } if(key.indexOf('.')>-1){ path=key.split('.'); attribute=path[0]; } var defs=AttributeSet.getDef(attribute,component); if(!$A.clientService.allowAccess(defs[0], defs[1])){ var message="Access Check Failed! AttributeSet.get(): attribute '"+attribute+"' of component '"+component+"' is not visible to '"+$A.clientService.currentAccess+"'."; if($A.clientService.enableAccessChecks){ if($A.clientService.logAccessFailures){ $A.error(null,new $A.auraError(message)); } return undefined; }else{ if($A.clientService.logAccessFailures){ $A.warning(message); } } } if (!path) { var decorators=this.decorators[key]; if(decorators&&decorators.length){ if(decorators.decorating){ value=decorators.value; }else{ decorators.decorating=true; decorators.value=this.values[key]; for(var i=0;i<decorators.length;i++){ var decorator=decorators[i]; value=decorator.value=decorators[i].evaluate(); } decorators.decorating=false; decorators.value=null; } }else{ value = this.values[key]; } } else { value = aura.expressionService.resolve(key, this.values); } if (aura.util.isExpression(value)) { value = value.evaluate(); } if(this.shadowValues.hasOwnProperty(key)) { value += this.getShadowValue(key); } return value; }; /** * simplified version of component.get('v.body'), * only supposed to be used by simple components. * * @private * */ AttributeSet.prototype.getBody = function(globalId) { var key = "body."+globalId; var value = this.values["body"][globalId]; if (aura.util.isExpression(value)) { value = value.evaluate(); } if(this.shadowValues.hasOwnProperty(key)) { value += this.getShadowValue(key); } return value; }; /** * simplified version of component.get('v.key'), * only supposed to be used by simple components. * * @private * */ AttributeSet.prototype.getValue = function(key) { var value = undefined; var decorators=this.decorators[key]; if(decorators&&decorators.length){ if(decorators.decorating){ value=decorators.value; }else{ decorators.decorating=true; decorators.value=this.values[key]; for(var i=0;i<decorators.length;i++){ var decorator=decorators[i]; value=decorator.value=decorators[i].evaluate(); } decorators.decorating=false; decorators.value=null; } }else{ value = this.values[key]; } if (aura.util.isExpression(value)) { value = value.evaluate(); } if(this.shadowValues.hasOwnProperty(key)) { value += this.getShadowValue(key); } return value; }; AttributeSet.prototype.getShadowValue=function(key){ var value = aura.expressionService.resolve(key, this.values, true); if(value instanceof FunctionCallValue){ if(this.shadowValues.hasOwnProperty(key)) { return this.shadowValues[key]; } return ''; } return undefined; }; AttributeSet.prototype.setShadowValue=function(key,value){ var oldValue = aura.expressionService.resolve(key, this.values, true); if(oldValue instanceof FunctionCallValue){ this.shadowValues[key]=value; } }; /** * Set the attribute of the given name to the given value. * * @param {String} * key The key can be a path expression inside. E.g. * attribute.nestedValue.value....} * @param {Object} * value The value to be set. * * @protected * */ AttributeSet.prototype.set = function(key, value, component) { var target = this.values; var path = null; var attribute=key; if (key.lastIndexOf("body", 0) === 0) { key=key.replace(/^body\b/g,"body."+component.globalId); } if(key.indexOf('.')>-1){ path=key.split('.'); attribute=path[0]; } var defs=AttributeSet.getDef(attribute,component); if(!$A.clientService.allowAccess(defs[0],defs[1])){ var message="Access Check Failed! AttributeSet.set(): '"+attribute+"' of component '"+component+"' is not visible to '"+$A.clientService.currentAccess+"'."; if($A.clientService.enableAccessChecks){ if($A.clientService.logAccessFailures){ $A.error(null,new $A.auraError(message)); } return; }else{ if($A.clientService.logAccessFailures){ $A.warning(message); } } } if(!$A.util.isUndefinedOrNull(value) && !this.isValueValidForAttribute(key, value)) { if(this.isTypeOfArray(key)) { value = !$A.util.isArray(value) ? [value] : value; } else { //$A.warning("You set the attribute '" + key + "' to the value '" + value + "' which was the wrong data type for the attribute."); // Do we want to allow. //return; } } // Process all keys except last one if (path) { var step = path.shift(); while (path.length > 0) { var nextStep = path.shift(); var nextTarget = target[step]; if (nextTarget === undefined) { // Attempt to do the right thing: create an empty object or an array // depending if the next indice is an object or an array. if (isNaN(nextStep)) { target[step] = {}; } else { target[step] = []; } target = target[step]; } else { if ($A.util.isExpression(nextTarget)) { target = nextTarget.evaluate(); } else { target = nextTarget; } } step = nextStep; } key = step; } // Check the type // FIXME: access checks: the test for the existence of defs[0] is only for when access checks are off. var attrType = defs[0] && defs[0].getTypeDefDescriptor(); var isFacet = attrType === "aura://Aura.Component[]"; if(isFacet && value) { var facet = value; if(!$A.util.isArray(facet)){ facet = [facet]; } // Change the parentId back pointer for each facet value. // Some facetValues are component def objects; ignore these // as the parent is irrelevant and its value provider will be // "component". var facetValue=null; for (var i = 0; i < facet.length; i++) { facetValue = facet[i]; if(facetValue) { while (facetValue instanceof PassthroughValue) { facetValue = facetValue.getComponent(); } // If the facet component has been rendered, its container should be the component who renders it. // TODO: why do we set container in here? probably for event bubbling. Figure it out and make it right. if (facetValue.setContainerComponentId && facetValue.isRendered() === false) { facetValue.setContainerComponentId(component.globalId); } } } } // We don't want to update the GVP from a component. // We do that from inside the GVP using $A.set() // So clear the reference and change if (target[key] instanceof PropertyReferenceValue && !target[key].isGlobal ) { target[key].set(value); } else if (!(target[key] instanceof FunctionCallValue)) { // HALO: TODO: JBUCH: I DON'T LIKE THIS... // Silently do nothing when you try to set on a FunctionCallValue, // which we need to support legacy old behaviour due to inheritance. target[key] = value; } // #if {"excludeModes" : ["PRODUCTION", "STATS"]} else { $A.warning("AttributeSet.set(): unable to override the value for '" + key + "=" + target[key] + "'. FunctionCallValues declared in markup are constant."); } // #end }; /** * Clears a property reference value of the given name, and returns it. Does nothing if the attribute * does not exist or is not a property reference value. * * @param {String} * key The key can be a path expression inside. E.g. * attribute.nestedValue.value....} * * @returns {PropertyReferenceValue} the reference that was found and cleared, or null * @protected * */ AttributeSet.prototype.clearReference = function(key) { var oldValue; var target=this.values; var step=key; if (key.indexOf('.') >= 0) { var path = key.split('.'); target = aura.expressionService.resolve(path.slice(0, path.length - 1), target); step=path[path.length-1]; } if(target) { oldValue = target[step]; if (oldValue instanceof PropertyReferenceValue) { target[step] = undefined; return oldValue; } } return null; }; /** * Verifies if a value is valid for the type that the attribute is defined as. * Strings as strings, arrays as arrays, etc. */ AttributeSet.prototype.isValueValidForAttribute = function(attributeName, value) { var attributeDefSet = this.attributeDefSet; if(attributeName.indexOf(".")>=0){ var path = attributeName.split("."); attributeName=path[0]; if(attributeName!=="body"&&path.length > 1) { // We don't validate setting a value 2 levels deep. (v.prop.subprop) return true; } } var attributeDef = attributeDefSet.getDef(attributeName); if(!attributeDef) { // Attribute doesn't exist on the component return false; } var nativeType = attributeDef.getNativeType(); // Do not validate property reference values or object types if($A.util.isExpression(value) || nativeType === "object") { return true; } // typeof [] == "object", so we need to do this one off for arrays. if(nativeType === "array") { return $A.util.isArray(value); } return typeof value === nativeType; }; AttributeSet.prototype.isTypeOfArray = function(attributeName) { if(attributeName.indexOf(".")>=0){ var path = attributeName.split("."); attributeName=path[0]; if(attributeName!=="body"&&path.length > 1) { // We don't validate setting a value 2 levels deep. (v.prop.subprop) return false; } } var attributeDef = this.attributeDefSet.getDef(attributeName); return attributeDef && attributeDef.getNativeType() === "array"; }; /** * Reset the attribute set to point at a different def set. * * Allows us to change the set of attributes in a set when we inject a new * component. No checking is done here, if checking is desired, it should be * done by the caller. * * Doesn't check the current state of attributes because they don't matter. This * will create/update attributes based on new AttributeDefSet, provided * attribute config and current attribute values * * @param {AttributeDefSet} * attributeDefSet the new def set to install. * @param {Object} * attributes - new attributes configuration * @private */ AttributeSet.prototype.merge = function(attributes, attributeDefSet, component) { if(attributeDefSet){ $A.assert(attributeDefSet instanceof AttributeDefSet, "AttributeSet.merge: A valid AttributeDefSet is required to merge attributes."); this.attributeDefSet = attributeDefSet; } // Reinitialize attribute values this.initialize(attributes,component); }; /** * Gets default attribute value. * * @param {String} * name - name of attribute * @private */ AttributeSet.prototype.getDefault = function(name) { if (name) { var attributeDef = this.attributeDefSet.getDef(name); if (attributeDef) { return attributeDef.getDefault(); } } return null; }; /** * Destroys the attributeset. * * @private */ AttributeSet.prototype.destroy = function() { var expressions = {}; if(!this.destroyed) { var values = this.values; for (var k in values) { var v = values[k]; // Body is special because it's a map // of bodies for each inheritance level // so we need to do a for-in loop if (k === "body") { for (var globalId in v) { var body = v[globalId]; if (body) { for (var j = 0; j < body.length; j++) { var bodyCmp = body[j]; if ($A.util.isComponent(bodyCmp) && bodyCmp.autoDestroy()) { bodyCmp.destroy(); } } } } values[k] = undefined; continue; } if ($A.util.isArray(v)) { for (var i = 0, value; i < v.length; i++) { value = v[i]; if ($A.util.isExpression(value)) { expressions[k] = value; } else if ($A.util.isComponent(value) && value.autoDestroy()) { value.destroy(); } } } else { if ($A.util.isExpression(v)) { expressions[k] = v; } else if ($A.util.isComponent(v) && v.autoDestroy()) { v.destroy(); } } values[k] = undefined; } this.destroyed = true; } return expressions; }; /** * Loop through AttributeDefSet and create or update value using provided config * * @param {Object} * config - attribute configuration * @private */ AttributeSet.prototype.initialize = function(attributes,component) { var attributeDefs = this.attributeDefSet.getValues(); var attributeNames = this.attributeDefSet.getNames(); if (!attributeDefs || !attributeNames) { return; } var configValues = attributes || {}; // Create known attributes and assign values or defaults for (var i = 0; i < attributeNames.length; i++) { var attributeDef = attributeDefs[attributeNames[i]]; var name = attributeDef.getDescriptor().getName(); var hasAttribute = this.hasAttribute(name); var hasValue = configValues.hasOwnProperty(name); var value = configValues[name]; if (!hasValue && !hasAttribute) { value = valueFactory.create(this.getDefault(name),component); hasValue = value !== undefined; } if ((hasValue && this.values[name]!==value) || !hasAttribute) { if(hasAttribute && value instanceof FunctionCallValue) { if (!this.decorators[name]) { this.decorators[name] = []; } this.decorators[name].push(value); }else{ if (!(value instanceof PropertyReferenceValue && value.equals(this.values[name]))) { this.values[name] = value; } } } } }; Aura.Attribute.AttributeSet = AttributeSet;
apache-2.0
jasarsoft/ipcs-primjeri
simple text editor/SimpleTextEditor/Properties/Settings.Designer.cs
1073
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SimpleTextEditor.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
apache-2.0
Pathfinder-Fr/YAFNET
yafsrc/YetAnotherForum.NET/Pages/admin/editlanguage.ascx.cs
19665
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2020 Ingo Herbote * https://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 * https://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. */ namespace YAF.Pages.Admin { #region Using using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.UI.WebControls; using System.Xml; using System.Xml.XPath; using YAF.Core; using YAF.Core.Utilities; using YAF.Types; using YAF.Types.Constants; using YAF.Types.Extensions; using YAF.Types.Interfaces; using YAF.Types.Objects; using YAF.Utils; using YAF.Utils.Helpers; using YAF.Web.Extensions; #endregion /// <summary> /// Administrative Page for the editing of forum properties. /// </summary> public partial class editlanguage : AdminPage { #region Constants and Fields /// <summary> /// Indicates if Xml File is Synchronized /// </summary> private bool update; /// <summary> /// Physical Path to The languages folder /// </summary> private string langPath; /// <summary> /// Xml File Name of Current Language /// </summary> private string xmlFile; /// <summary> /// The translations. /// </summary> private List<Translation> translations = new List<Translation>(); #endregion #region Properties /// <summary> /// Gets the List of attributes for Resources in destination translation file /// </summary> private StringDictionary ResourcesAttributes { get; } = new StringDictionary(); /// <summary> /// Gets the List of namespaces for Resources in destination translation file /// </summary> private StringDictionary ResourcesNamespaces { get; } = new StringDictionary(); #endregion #region Public Methods /// <summary> /// Remove all Resources with the same Name and Page /// </summary> /// <typeparam name="T">The typed parameter</typeparam> /// <param name="list">The list.</param> /// <returns> /// The Cleaned List /// </returns> [NotNull] public static List<T> RemoveDuplicateSections<T>([NotNull] List<T> list) where T : Translation { var finalList = new List<T>(); finalList.AddRange( list.Where( item1 => finalList.Find( check => check.PageName.Equals(item1.PageName) && check.ResourceName.Equals(item1.ResourceName)) == null)); return finalList; } /// <summary> /// Compare source and destination values on focus lost and indicate (guess) whether text is translated or not /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param> public void LocalizedTextCheck([NotNull] object sender, [NotNull] ServerValidateEventArgs args) { foreach (var tbx in this.grdLocals.Items.Cast<DataGridItem>() .Select(item => item.FindControlAs<TextBox>("txtLocalized")).Where(tbx => args.Value.Equals(tbx.Text))) { tbx.ForeColor = tbx.Text.Equals(tbx.ToolTip, StringComparison.OrdinalIgnoreCase) ? Color.Red : Color.Black; break; } args.IsValid = true; } #endregion #region Methods /// <summary>Raises the <see cref="E:System.Web.UI.Control.Init"/> event.</summary> /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnInit([NotNull] EventArgs e) { this.InitializeComponent(); base.OnInit(e); } /// <summary> /// Registers the needed Java Scripts /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnPreRender([NotNull] EventArgs e) { BoardContext.Current.PageElements.RegisterJsBlock( "FixGridTableJs", JavaScriptBlocks.FixGridTable(this.grdLocals.ClientID)); base.OnPreRender(e); } /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { this.langPath = HttpContext.Current.Request.MapPath($"{BoardInfo.ForumServerFileRoot}languages"); if (this.Get<HttpRequestBase>().QueryString.Exists("x")) { this.xmlFile = this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("x"); this.dDLPages.Items.Clear(); this.PopulateTranslations( Path.Combine(this.langPath, "english.xml"), Path.Combine(this.langPath, this.xmlFile)); } if (this.IsPostBack) { return; } this.dDLPages.Items.FindByText("DEFAULT").Selected = true; this.lblPageName.Text = "DEFAULT"; if (this.update) { this.Info.Visible = true; this.lblInfo.Text = this.GetText("ADMIN_EDITLANGUAGE", "AUTO_SYNC"); this.SaveLanguageFile(); } else { this.Info.Visible = false; } this.grdLocals.DataSource = this.translations.FindAll(check => check.PageName.Equals("DEFAULT")); this.grdLocals.DataBind(); } /// <summary> /// Creates page links for this page. /// </summary> protected override void CreatePageLinks() { this.PageLinks.AddRoot(); this.PageLinks.AddLink( this.GetText("ADMIN_ADMIN", "Administration"), BuildLink.GetLink(ForumPages.admin_admin)); this.PageLinks.AddLink( this.GetText("ADMIN_LANGUAGES", "TITLE"), BuildLink.GetLink(ForumPages.admin_languages)); this.PageLinks.AddLink(this.GetText("ADMIN_EDITLANGUAGE", "TITLE"), string.Empty); this.Page.Header.Title = $"{this.GetText("ADMIN_ADMIN", "Administration")} - {this.GetText("ADMIN_LANGUAGES", "TITLE")} - {this.GetText("ADMIN_EDITLANGUAGE", "TITLE")}"; } /// <summary> /// Returns Back to The Languages Page /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private static void CancelClick([NotNull] object sender, [NotNull] EventArgs e) { BuildLink.Redirect(ForumPages.admin_languages); } /// <summary> /// Checks if Resources are translated and handle Size of the Textboxes based on the Content Length /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.DataGridItemEventArgs"/> instance containing the event data.</param> private static void GrdLocalsItemDataBound([NotNull] object sender, [NotNull] DataGridItemEventArgs e) { if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) { return; } var txtLocalized = e.Item.FindControlAs<TextBox>("txtLocalized"); var txtResource = e.Item.FindControlAs<TextBox>("txtResource"); if (txtResource.Text.Length > 30) { // int height = 80 * (txtSource.Text.Length / 80); txtResource.TextMode = TextBoxMode.MultiLine; txtResource.Height = Unit.Pixel(80); txtLocalized.TextMode = TextBoxMode.MultiLine; txtLocalized.Height = Unit.Pixel(80); } if (txtLocalized.Text.Equals(txtResource.Text, StringComparison.OrdinalIgnoreCase)) { txtLocalized.ForeColor = Color.Red; } } /// <summary> /// Creates controls for column 1 (Resource tag) and column 2 (Resource value). /// </summary> /// <param name="pageName">Name of the page.</param> /// <param name="resourceName">Name of the resource.</param> /// <param name="srcResourceValue">The SRC resource value.</param> /// <param name="dstResourceValue">The DST resource value.</param> private void CreatePageResourceControl( [NotNull] string pageName, [NotNull] string resourceName, [NotNull] string srcResourceValue, [NotNull] string dstResourceValue) { var translation = new Translation { PageName = pageName, ResourceName = resourceName, ResourceValue = srcResourceValue, LocalizedValue = dstResourceValue }; this.translations.Add(translation); } /// <summary> /// Creates a header row in the Resource Page DropDown Header text is page section name in XML file. /// </summary> /// <param name="pageName">Name of the page.</param> private void CreatePageResourceHeader([NotNull] string pageName) { this.dDLPages.Items.Add(new ListItem(pageName, pageName)); } /// <summary> /// The initialize component. /// </summary> private void InitializeComponent() { this.btnLoadPageLocalization.Click += this.LoadPageLocalization; this.btnCancel.Click += CancelClick; this.btnSave.Click += this.SaveClick; this.grdLocals.ItemDataBound += GrdLocalsItemDataBound; } /// <summary> /// Load Selected Page Resources /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void LoadPageLocalization([NotNull] object sender, [NotNull] EventArgs e) { // Save Values this.UpdateLocalizedValues(); this.SaveLanguageFile(); this.lblPageName.Text = this.dDLPages.SelectedValue; this.grdLocals.DataSource = this.translations.FindAll(check => check.PageName.Equals(this.dDLPages.SelectedValue)); this.grdLocals.DataBind(); } /// <summary> /// Wraps creation of translation controls. /// </summary> /// <param name="srcFile">The SRC file.</param> /// <param name="dstFile">The DST file.</param> private void PopulateTranslations([NotNull] string srcFile, [NotNull] string dstFile) { this.update = false; try { var docSrc = new XmlDocument(); var docDst = new XmlDocument(); docSrc.Load(srcFile); docDst.Load(dstFile); var navSrc = docSrc.DocumentElement.CreateNavigator(); var navDst = docDst.DocumentElement.CreateNavigator(); this.ResourcesNamespaces.Clear(); if (navDst.MoveToFirstNamespace()) { do { this.ResourcesNamespaces.Add(navDst.Name, navDst.Value); } while (navDst.MoveToNextNamespace()); } navDst.MoveToRoot(); navDst.MoveToFirstChild(); this.ResourcesAttributes.Clear(); if (navDst.MoveToFirstAttribute()) { do { this.ResourcesAttributes.Add(navDst.Name, navDst.Value); } while (navDst.MoveToNextAttribute()); } navDst.MoveToRoot(); navDst.MoveToFirstChild(); foreach (XPathNavigator pageItemNavigator in navSrc.Select("page")) { // int pageResourceCount = 0; var pageNameAttributeValue = pageItemNavigator.GetAttribute("name", string.Empty); this.CreatePageResourceHeader(pageNameAttributeValue); var resourceItemCollection = pageItemNavigator.Select("Resource"); foreach (XPathNavigator resourceItem in resourceItemCollection) { var resourceTagAttributeValue = resourceItem.GetAttribute("tag", string.Empty); var iteratorSe = navDst.Select( $"/Resources/page[@name=\"{pageNameAttributeValue}\"]/Resource[@tag=\"{resourceTagAttributeValue}\"]"); if (iteratorSe.Count <= 0) { // pageResourceCount++; // Generate Missing Languages this.CreatePageResourceControl( pageNameAttributeValue, resourceTagAttributeValue, resourceItem.Value, resourceItem.Value); this.update = true; } while (iteratorSe.MoveNext()) { // pageResourceCount++; if (!iteratorSe.Current.Value.Equals( resourceItem.Value, StringComparison.OrdinalIgnoreCase)) { } this.CreatePageResourceControl( pageNameAttributeValue, resourceTagAttributeValue, resourceItem.Value, iteratorSe.Current.Value); } } } } catch (Exception exception) { this.Logger.Log(null, this, $"Error loading files. {exception.Message}"); } } /// <summary> /// Save the Updated Xml File /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void SaveClick([NotNull] object sender, [NotNull] EventArgs e) { this.UpdateLocalizedValues(); this.SaveLanguageFile(); } /// <summary> /// Save the Updated Xml File. /// </summary> private void SaveLanguageFile() { this.translations = RemoveDuplicateSections(this.translations); var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, OmitXmlDeclaration = false, Indent = true, IndentChars = " " }; var xw = XmlWriter.Create(Path.Combine(this.langPath, this.xmlFile), settings); xw.WriteStartDocument(); // <Resources> xw.WriteStartElement("Resources"); foreach (string key in this.ResourcesNamespaces.Keys) { xw.WriteAttributeString("xmlns", key, null, this.ResourcesNamespaces[key]); } foreach (string key in this.ResourcesAttributes.Keys) { xw.WriteAttributeString(key, this.ResourcesAttributes[key]); } var currentPageName = string.Empty; foreach (var trans in this.translations.OrderBy(t => t.PageName).ThenBy(t => t.ResourceName)) { // <page></page> if (!trans.PageName.Equals(currentPageName, StringComparison.OrdinalIgnoreCase)) { if (currentPageName.IsSet()) { xw.WriteFullEndElement(); } currentPageName = trans.PageName; xw.WriteStartElement("page"); xw.WriteAttributeString("name", currentPageName); } xw.WriteStartElement("Resource"); xw.WriteAttributeString("tag", trans.ResourceName); xw.WriteString(trans.LocalizedValue); xw.WriteFullEndElement(); } // final </page> if (currentPageName.IsSet()) { xw.WriteFullEndElement(); } // </Resources> xw.WriteFullEndElement(); xw.WriteEndDocument(); xw.Close(); HttpRuntime.UnloadAppDomain(); } /// <summary> /// Update Localized Values in the Generics List /// </summary> private void UpdateLocalizedValues() { this.grdLocals.Items.Cast<DataGridItem>().ForEach( item => { var txtLocalized = item.FindControlAs<TextBox>("txtLocalized"); var lblResourceName = item.FindControlAs<Label>("lblResourceName"); this.translations.Find( check => check.PageName.Equals(this.lblPageName.Text) && check.ResourceName.Equals(lblResourceName.Text)).LocalizedValue = txtLocalized.Text; }); } #endregion } }
apache-2.0
aml-development/ozp-backend
ozpcenter/api/listing/model_access_es.py
14763
""" Listing Model Access For Elasticsearch Code was developed to work with Elasticsearch 2.4.* TODO: Refactor Elasticsearch Code """ import json import logging from django.conf import settings from django.http.request import QueryDict from rest_framework import serializers from ozpcenter.api.listing.elasticsearch_util import elasticsearch_factory from ozpcenter.api.listing import elasticsearch_util from ozpcenter import constants from ozpcenter import models from ozpcenter import utils from plugins import plugin_manager system_has_access_control = plugin_manager.system_has_access_control logger = logging.getLogger('ozp-center.' + str(__name__)) class SearchParamParser(object): """ Parser for Search Parameters Filter_params can contain - filter_params * List of category names (OR logic) * List of agencies (OR logic) * List of listing types (OR logic) """ def __init__(self, request): self.base_url = '{scheme}://{host}'.format(scheme=request.scheme, host=request.get_host()) self.search_string = request.query_params.get('search', None) if self.search_string: try: self.search_string = str(self.search_string).strip() except: self.search_string = None if request.query_params.get('limit', False): self.limit_set = True else: self.limit_set = False try: self.offset = int(request.query_params.get('offset', 0)) except: self.offset = 0 try: self.limit = int(request.query_params.get('limit', 100)) except: self.limit = 100 # Filtering self.tags = [str(record) for record in request.query_params.getlist('tag', [])] self.categories = [str(record) for record in request.query_params.getlist('category', [])] self.agencies = [str(record) for record in request.query_params.getlist('agency', [])] self.listing_types = [str(record) for record in request.query_params.getlist('type', [])] self.is_508_compliant = None # Override is_508_compliant if self.request.user.profile.only_508_search_flag is true if request.user.profile.only_508_search_flag is True: self.is_508_compliant = True # Override is_508_compliant via params self.is_508_compliant_params = request.query_params.get('is_508_compliant', '').strip() # Can be None, False, True if self.is_508_compliant_params: self.is_508_compliant = utils.str_to_bool(self.is_508_compliant_params) # Ordering Example: api/listings/essearch/?search=&limit=24&offset=24&ordering=-title self.ordering = [str(record) for record in request.query_params.getlist('ordering', [])] # Minscore try: self.min_score = float(request.query_params.get('minscore', constants.ES_MIN_SCORE)) except: self.min_score = constants.ES_MIN_SCORE # Boost - Title try: self.boost_title = float(request.query_params.get('bti', constants.ES_BOOST_TITLE)) except: self.boost_title = constants.ES_BOOST_TITLE # Boost - Description try: self.boost_description = float(request.query_params.get('bde', constants.ES_BOOST_DESCRIPTION)) except: self.boost_description = constants.ES_BOOST_DESCRIPTION # Boost - Short Description try: self.boost_description_short = float(request.query_params.get('bds', constants.ES_BOOST_DESCRIPTION_SHORT)) except: self.boost_description_short = constants.ES_BOOST_DESCRIPTION_SHORT # Boost - Tags try: self.boost_tags = float(request.query_params.get('btg', constants.ES_BOOST_TAGS)) except: self.boost_tags = constants.ES_BOOST_TAGS def __str__(self): """ Convert SearchParamParser Object into JSON String Representation """ temp_dict = {'SearchParamParser': vars(self)} return json.dumps(temp_dict) def recreate_index_mapping(): """ Recreate Index Mapping """ index_mapping = elasticsearch_util.get_mapping_setting_obj() elasticsearch_factory.recreate_index_mapping(settings.ES_INDEX_NAME, index_mapping) class ReadOnlyListingSerializer(serializers.ModelSerializer): """ Serializer used to convert listing object into python friendly object """ class Meta: model = models.Listing depth = 2 fields = '__all__' def bulk_reindex(): """ Reindex Listing Data into an Elasticsearch Index Steps: Checks to see if elasticsearch connection is good Removes the index if it already exist Creates the index with mapping Reindex data Wait for the cluster health to turn yellow To check index in elasticsearch: http://127.0.0.1:9200/appsmall/_search?size=10000&pretty """ # Create ES client es_client = elasticsearch_factory.get_client() logger.debug('Starting Indexing Process') elasticsearch_factory.check_elasticsearch() recreate_index_mapping() # Convert Listing Objects into Python Objects # Had to add order_by for test_essearch_is_enable to pass for both sqlite/postgresql # TODO: Investigate if results coming back from elasticsearch is order by 'Relevance score' all_listings = models.Listing.objects.order_by('id').all() serializer = ReadOnlyListingSerializer(all_listings, many=True) serializer_results = serializer.data bulk_data = [] for record in serializer_results: # Transform Serializer records into records for elasticsearch record_clean_obj = elasticsearch_util.prepare_clean_listing_record(record) op_dict = { 'index': { '_index': settings.ES_INDEX_NAME, '_type': settings.ES_TYPE_NAME, '_id': record_clean_obj[settings.ES_ID_FIELD] } } bulk_data.append(op_dict) bulk_data.append(record_clean_obj) # Bulk index the data logger.debug('Bulk indexing listings...') res = es_client.bulk(index=settings.ES_INDEX_NAME, body=bulk_data, refresh=True) if res.get('errors', True): logger.error('Error Bulk Indexing') else: logger.debug('Bulk Indexing Successful') logger.debug('Waiting for cluster to turn yellow') es_client.cluster.health(wait_for_status='yellow', request_timeout=20) logger.debug('Finish waiting for cluster to turn yellow') def get_user_exclude_orgs(username): """ Get User's Orgs to exclude """ # TODO: Refactor to use Model.get_user_exclude_orgs, code duplication exclude_orgs = None user = models.Profile.objects.get(user__username=username) # Filter out private listings - private apps (apps only from user's agency) requirement if user.highest_role() == 'APPS_MALL_STEWARD': exclude_orgs = [] elif user.highest_role() == 'ORG_STEWARD': user_orgs = user.stewarded_organizations.all() user_orgs = [i.title for i in user_orgs] exclude_orgs_obj = models.Agency.objects.exclude(title__in=user_orgs) exclude_orgs = [agency.short_name for agency in exclude_orgs_obj] else: user_orgs = user.organizations.all() user_orgs = [i.title for i in user_orgs] exclude_orgs_obj = models.Agency.objects.exclude(title__in=user_orgs) exclude_orgs = [agency.short_name for agency in exclude_orgs_obj] return exclude_orgs def suggest(request_username, search_param_parser): """ Suggest It must respects restrictions - Private apps (apps only from user's agency) - User's max_classification_level Args: request_username(string) search_param_parser(SearchParamParser): Parsed Request Search Object Returns: listing titles in a list """ es_client = elasticsearch_factory.get_client() elasticsearch_factory.check_elasticsearch() if search_param_parser.search_string is None: return [] user_exclude_orgs = get_user_exclude_orgs(request_username) # Override Limit - Only 15 results should come if limit was not set if search_param_parser.limit_set is False: search_param_parser.limit = constants.ES_SUGGEST_LIMIT search_query = elasticsearch_util.make_search_query_obj(search_param_parser, exclude_agencies=user_exclude_orgs) # Only Retrieve ['title', 'security_marking', 'id'] fields from Elasticsearch for suggestions search_query['_source'] = ['title', 'security_marking', 'id'] # print(json.dumps(search_query, indent=4)) # Print statement for debugging output res = es_client.search(index=settings.ES_INDEX_NAME, body=search_query) hits = res.get('hits', {}).get('hits', None) if not hits: return [] hit_titles = [] for hit in hits: source = hit.get('_source') exclude_bool = False if not source.get('security_marking'): exclude_bool = True logger.debug('Listing {0!s} has no security_marking'.format(source.get('title'))) if not system_has_access_control(request_username, source.get('security_marking')): exclude_bool = True if exclude_bool is False: temp = {'title': source['title'], 'id': source['id']} hit_titles.append(temp) return hit_titles def generate_link(search_param_parser, offset_prediction): """ Generate next/previous URL links Args: search_param_parser(SearchParamParser): Parsed Request Search Object offset_prediction: offset prediction number Returns: URL for next/previous links (string) """ query_temp = QueryDict(mutable=True) query_temp.update({'search': search_param_parser.search_string}) query_temp.update({'offset': offset_prediction}) query_temp.update({'limit': search_param_parser.limit}) # Limit stays the same [query_temp.update({'category': current_category}) for current_category in search_param_parser.categories] [query_temp.update({'agency': current_category}) for current_category in search_param_parser.agencies] [query_temp.update({'type': current_category}) for current_category in search_param_parser.listing_types] return '{!s}/api/listings/essearch/?{!s}'.format(search_param_parser.base_url, query_temp.urlencode()) def search(request_username, search_param_parser): """ Filter Listings Too many variations to cache results Users shall be able to search for listings' - title - description - description_short - tags__name Filter by - category - agency - listing types - is_508_compliant Users shall only see what they are authorized to see 'is_private': false, 'approval_status': 'APPROVED', 'is_deleted': false, 'is_enabled': true, 'security_marking': 'UNCLASSIFIED', Sorted by Relevance 'avg_rate': 0, 'total_votes': 0, 'total_rate5': 0, 'total_rate4': 0, 'total_rate3': 0, 'total_rate2': 0, 'total_rate1': 0, 'total_reviews': 0, 'is_featured': true, It must respects restrictions - Private apps (apps only from user's agency) - User's max_classification_level Args: username(str): username search_param_parser(SearchParamParser): parameters """ elasticsearch_factory.check_elasticsearch() # Create ES client es_client = elasticsearch_factory.get_client() user_exclude_orgs = get_user_exclude_orgs(request_username) search_query = elasticsearch_util.make_search_query_obj(search_param_parser, exclude_agencies=user_exclude_orgs) try: res = es_client.search(index=settings.ES_INDEX_NAME, body=search_query) except Exception as err: print(json.dumps(search_query, indent=4)) raise err hits = res.get('hits', {}) inner_hits = hits.get('hits', None) if not hits: return [] hit_titles = [] excluded_count = 0 for current_innter_hit in inner_hits: source = current_innter_hit.get('_source') source['_score'] = current_innter_hit.get('_score') # Add URLs to icons image_keys_to_add_url = ['large_icon', 'small_icon', 'banner_icon', 'large_banner_icon'] for image_key in image_keys_to_add_url: if source.get(image_key) is not None: if search_param_parser.base_url: source[image_key]['url'] = '{!s}/api/image/{!s}/'.format(search_param_parser.base_url, source[image_key]['id']) else: source[image_key]['url'] = '/api/image/{!s}/'.format(source[image_key]['id']) exclude_bool = False if not source.get('security_marking'): exclude_bool = True logger.debug('Listing {0!s} has no security_marking'.format(source.get('title'))) if not system_has_access_control(request_username, source.get('security_marking')): exclude_bool = True if exclude_bool is False: hit_titles.append(source) else: excluded_count = excluded_count + 1 # Total Records in Elasticsearch final_count = hits.get('total') # Total Records minus what the user does not have access to see, this count should never be below zero # TODO: Figure out smarter logic for excluded_count compensation (rivera 11/14/2016) final_count_with_excluded = final_count - excluded_count final_results = { 'count': final_count_with_excluded, 'results': hit_titles } final_results['previous'] = None final_results['next'] = None # if final_count_with_excluded < 0 then previous and next should be None if final_count_with_excluded < 0: return final_results previous_offset_prediction = search_param_parser.offset - search_param_parser.limit next_offset_prediction = search_param_parser.offset + search_param_parser.limit final_results['next_offset_prediction'] = next_offset_prediction # Previous URL - previous_offset_prediction is less than zero, previous should be None if previous_offset_prediction >= 0: final_results['previous'] = generate_link(search_param_parser, previous_offset_prediction) # Next URL if next_offset_prediction <= final_count_with_excluded: final_results['next'] = generate_link(search_param_parser, next_offset_prediction) return final_results
apache-2.0
vladn-ma/vladn-ovs-doc
doxygen/ovs_all/html/structL2Key.js
641
var structL2Key = [ [ "dlDst", "structL2Key.html#ae1cdfc72687279c1c8218a20d6cd233f", null ], [ "dlSrc", "structL2Key.html#ab119d53d14196c197bce5e4d7c2a7a98", null ], [ "dlType", "structL2Key.html#a4e93d93f429dd30cc547b6f41b879efa", null ], [ "inPort", "structL2Key.html#a0fd29f40d5dad469aa5080135013bbd1", null ], [ "keyLen", "structL2Key.html#ad19eae10dd6f2985ac0893385c962786", null ], [ "offset", "structL2Key.html#a3f7390a6128d37a53bb807949065992b", null ], [ "val", "structL2Key.html#a4ab08ee2a99c70acb3bd5d786acb53a7", null ], [ "vlanTci", "structL2Key.html#aefb0ef535bac2cc50e9fa85c7e39bb27", null ] ];
apache-2.0
VishwasShashidhar/SymphonyElectron
src/app/window-actions.ts
18610
import { BrowserWindow, dialog, PermissionRequestHandlerHandlerDetails, systemPreferences, } from 'electron'; import { apiName, IBoundsChange, KeyCodes } from '../common/api-interface'; import { isLinux, isMac, isWindowsOS } from '../common/env'; import { i18n } from '../common/i18n'; import { logger } from '../common/logger'; import { throttle } from '../common/utils'; import { notification } from '../renderer/notification'; import { CloudConfigDataTypes, config } from './config-handler'; import { ICustomBrowserWindow, windowHandler } from './window-handler'; import { showPopupMenu, windowExists } from './window-utils'; enum Permissions { MEDIA = 'media', LOCATION = 'geolocation', NOTIFICATIONS = 'notifications', MIDI_SYSEX = 'midiSysex', POINTER_LOCK = 'pointerLock', FULL_SCREEN = 'fullscreen', OPEN_EXTERNAL = 'openExternal', } const PERMISSIONS_NAMESPACE = 'Permissions'; const saveWindowSettings = async (): Promise<void> => { const browserWindow = BrowserWindow.getFocusedWindow() as ICustomBrowserWindow; const mainWindow = windowHandler.getMainWindow(); if (browserWindow && windowExists(browserWindow)) { let [x, y] = browserWindow.getPosition(); let [width, height] = browserWindow.getSize(); if (x && y && width && height) { // Only send bound changes over to client for pop-out windows if ( browserWindow.winName !== apiName.mainWindowName && mainWindow && windowExists(mainWindow) ) { const boundsChange: IBoundsChange = { x, y, width, height, windowName: browserWindow.winName, }; mainWindow.webContents.send('boundsChange', boundsChange); } // Update the config file if (browserWindow.winName === apiName.mainWindowName) { const isMaximized = browserWindow.isMaximized(); const isFullScreen = browserWindow.isFullScreen(); const { mainWinPos } = config.getUserConfigFields(['mainWinPos']); if (isMaximized || isFullScreen) { // Keep the original size and position when window is maximized or full screen if ( mainWinPos !== undefined && mainWinPos.x !== undefined && mainWinPos.y !== undefined && mainWinPos.width !== undefined && mainWinPos.height !== undefined ) { x = mainWinPos.x; y = mainWinPos.y; width = mainWinPos.width; height = mainWinPos.height; } } await config.updateUserConfig({ mainWinPos: { ...mainWinPos, ...{ height, width, x, y, isMaximized, isFullScreen }, }, }); } } } }; const windowMaximized = async (): Promise<void> => { const browserWindow = BrowserWindow.getFocusedWindow() as ICustomBrowserWindow; if (browserWindow && windowExists(browserWindow)) { const isMaximized = browserWindow.isMaximized(); const isFullScreen = browserWindow.isFullScreen(); if (browserWindow.winName === apiName.mainWindowName) { const { mainWinPos } = config.getUserConfigFields(['mainWinPos']); await config.updateUserConfig({ mainWinPos: { ...mainWinPos, ...{ isMaximized, isFullScreen } }, }); } } }; const throttledWindowChanges = throttle(async () => { await saveWindowSettings(); await windowMaximized(); notification.moveNotificationToTop(); }, 1000); const throttledWindowRestore = throttle(async () => { notification.moveNotificationToTop(); }, 1000); /** * Sends initial bound changes for pop-out windows * * @param childWindow {BrowserWindow} - window created via new-window event */ export const sendInitialBoundChanges = (childWindow: BrowserWindow): void => { logger.info(`window-actions: Sending initial bounds`); const mainWindow = windowHandler.getMainWindow(); if (!mainWindow || !windowExists(mainWindow)) { return; } if (!childWindow || !windowExists(childWindow)) { logger.error( `window-actions: child window has already been destroyed - not sending bound change`, ); return; } const { x, y, width, height } = childWindow.getBounds(); const windowName = (childWindow as ICustomBrowserWindow).winName; const boundsChange: IBoundsChange = { x, y, width, height, windowName, }; mainWindow.webContents.send('boundsChange', boundsChange); logger.info( `window-actions: Initial bounds sent for ${ (childWindow as ICustomBrowserWindow).winName }`, { x, y, width, height }, ); }; /** * Tries finding a window we have created with given name. If found, then * brings to front and gives focus. * * @param {string} windowName Name of target window. Note: main window has * name 'main'. * @param {Boolean} shouldFocus whether to get window to focus or just show * without giving focus */ export const activate = ( windowName: string, shouldFocus: boolean = true, ): void => { // Electron-136: don't activate when the app is reloaded programmatically if (windowHandler.isAutoReload) { return; } const windows = windowHandler.getAllWindows(); for (const key in windows) { if (Object.prototype.hasOwnProperty.call(windows, key)) { const window = windows[key]; if (window && !window.isDestroyed() && window.winName === windowName) { // Bring the window to the top without focusing // Flash task bar icon in Windows for windows if (!shouldFocus) { return isMac || isLinux ? window.showInactive() : window.flashFrame(true); } // Note: On window just focusing will preserve window snapped state // Hiding the window and just calling the focus() won't display the window if (isWindowsOS) { return window.isMinimized() ? window.restore() : window.focus(); } return window.isMinimized() ? window.restore() : window.show(); } } } }; /** * Sets always on top property based on isAlwaysOnTop * * @param shouldSetAlwaysOnTop {boolean} - Whether to enable always on top or not * @param shouldActivateMainWindow {boolean} - Whether to active main window * @param shouldUpdateUserConfig {boolean} - whether to update config file */ export const updateAlwaysOnTop = async ( shouldSetAlwaysOnTop: boolean, shouldActivateMainWindow: boolean = true, shouldUpdateUserConfig: boolean = true, ): Promise<void> => { logger.info( `window-actions: Should we set always on top? ${shouldSetAlwaysOnTop}!`, ); const browserWins: ICustomBrowserWindow[] = BrowserWindow.getAllWindows() as ICustomBrowserWindow[]; if (shouldUpdateUserConfig) { await config.updateUserConfig({ alwaysOnTop: shouldSetAlwaysOnTop ? CloudConfigDataTypes.ENABLED : CloudConfigDataTypes.NOT_SET, }); } if (browserWins.length > 0) { browserWins .filter((browser) => typeof browser.notificationData !== 'object') .forEach((browser) => browser.setAlwaysOnTop(shouldSetAlwaysOnTop)); // An issue where changing the alwaysOnTop property // focus the pop-out window // Issue - Electron-209/470 const mainWindow = windowHandler.getMainWindow(); if (mainWindow && mainWindow.winName && shouldActivateMainWindow) { activate(mainWindow.winName); logger.info(`window-actions: activated main window!`); } } }; /** * Method that handles key press * * @param key {number} */ export const handleKeyPress = (key: number): void => { switch (key) { case KeyCodes.Esc: { const focusedWindow = BrowserWindow.getFocusedWindow(); if ( focusedWindow && !focusedWindow.isDestroyed() && focusedWindow.isFullScreen() ) { logger.info(`window-actions: exiting fullscreen by esc key action`); focusedWindow.setFullScreen(false); } break; } case KeyCodes.Alt: if (isMac || isLinux || windowHandler.isCustomTitleBar) { return; } const browserWin = BrowserWindow.getFocusedWindow() as ICustomBrowserWindow; if ( browserWin && windowExists(browserWin) && browserWin.winName === apiName.mainWindowName ) { logger.info(`window-actions: popping up menu by alt key action`); showPopupMenu({ window: browserWin }); } break; default: break; } }; /** * Sets the window to always on top based * on fullscreen state */ const setSpecificAlwaysOnTop = () => { const browserWindow = BrowserWindow.getFocusedWindow(); if ( isMac && browserWindow && windowExists(browserWindow) && browserWindow.isAlwaysOnTop() ) { // Set the focused window's always on top level based on fullscreen state browserWindow.setAlwaysOnTop( true, browserWindow.isFullScreen() ? 'modal-panel' : 'floating', ); } }; /** * Monitors window actions * * @param window {BrowserWindow} */ export const monitorWindowActions = (window: BrowserWindow): void => { if (windowHandler.shouldShowWelcomeScreen) { logger.info( `Not saving window position as we are showing the welcome window!`, ); return; } if (!window || window.isDestroyed()) { return; } const eventNames = ['move', 'resize']; eventNames.forEach((event: string) => { if (window) { // @ts-ignore window.on(event, throttledWindowChanges); } }); window.on('enter-full-screen', throttledWindowChanges); window.on('maximize', throttledWindowChanges); window.on('leave-full-screen', throttledWindowChanges); window.on('unmaximize', throttledWindowChanges); if ((window as ICustomBrowserWindow).winName === apiName.mainWindowName) { window.on('restore', throttledWindowRestore); } // Workaround for an issue with MacOS + AlwaysOnTop // Issue: SDA-1665 if (isMac) { window.on('enter-full-screen', setSpecificAlwaysOnTop); window.on('leave-full-screen', setSpecificAlwaysOnTop); } }; /** * Removes attached event listeners * * @param window */ export const removeWindowEventListener = (window: BrowserWindow): void => { if (!window || window.isDestroyed()) { return; } const eventNames = ['move', 'resize']; eventNames.forEach((event: string) => { if (window) { // @ts-ignore window.removeListener(event, throttledWindowChanges); } }); window.removeListener('enter-full-screen', throttledWindowChanges); window.removeListener('maximize', throttledWindowChanges); window.removeListener('leave-full-screen', throttledWindowChanges); window.removeListener('unmaximize', throttledWindowChanges); // Workaround for and issue with MacOS + AlwaysOnTop // Issue: SDA-1665 if (isMac) { window.removeListener('enter-full-screen', setSpecificAlwaysOnTop); window.removeListener('leave-full-screen', setSpecificAlwaysOnTop); } }; /** * Verifies the permission and display a * dialog if the action is not enabled * * @param permission {boolean} - config value to a specific permission * @param message {string} - custom message displayed to the user * @param callback {function} */ export const handleSessionPermissions = async ( permission: boolean, message: string, callback: (permission: boolean) => void, ): Promise<void> => { logger.info(`window-action: permission is ->`, { type: message, permission }); if (!permission) { const browserWindow = BrowserWindow.getFocusedWindow(); if (browserWindow && !browserWindow.isDestroyed()) { const response = await dialog.showMessageBox(browserWindow, { type: 'error', title: `${i18n.t('Permission Denied')()}!`, message, }); logger.error( `window-actions: permissions message box closed with response`, response, ); } } return callback(permission); }; /** * Modified version of handleSessionPermissions that takes an additional details param. * * Verifies the permission both against SDA permissions, and systemPermissions (macOS only). * Displays a dialog if permission is disabled by administrator * * @param permission {boolean} - config value to a specific permission (only supports media permissions) * @param message {string} - custom message displayed to the user * @param callback {function} * @param details {PermissionRequestHandlerHandlerDetails} - object passed along with certain permission types. see {@link https://www.electronjs.org/docs/api/session#sessetpermissionrequesthandlerhandler} */ const handleMediaPermissions = async ( permission: boolean, message: string, callback: (permission: boolean) => void, details: PermissionRequestHandlerHandlerDetails, ): Promise<void> => { logger.info(`window-action: permission is ->`, { type: message, permission }); let systemAudioPermission; let systemVideoPermission; if (isMac) { systemAudioPermission = await systemPreferences.askForMediaAccess( 'microphone', ); systemVideoPermission = await systemPreferences.askForMediaAccess('camera'); } else { systemAudioPermission = true; systemVideoPermission = true; } if (!permission) { const browserWindow = BrowserWindow.getFocusedWindow(); if (browserWindow && !browserWindow.isDestroyed()) { const response = await dialog.showMessageBox(browserWindow, { type: 'error', title: `${i18n.t('Permission Denied')()}!`, message, }); logger.error( `window-actions: permissions message box closed with response`, response, ); } } if (details.mediaTypes && isMac) { if (details.mediaTypes.includes('audio') && !systemAudioPermission) { return callback(false); } if (details.mediaTypes.includes('video') && !systemVideoPermission) { return callback(false); } } return callback(permission); }; /** * Sets permission requests for the window * * @param webContents {Electron.webContents} */ export const handlePermissionRequests = ( webContents: Electron.webContents, ): void => { if (!webContents || !webContents.session) { return; } const { session } = webContents; const { permissions } = config.getConfigFields(['permissions']); if (!permissions) { logger.error( 'permissions configuration is invalid, so, everything will be true by default!', ); return; } session.setPermissionRequestHandler( (_webContents, permission, callback, details) => { switch (permission) { case Permissions.MEDIA: return handleMediaPermissions( permissions.media, i18n.t( 'Your administrator has disabled sharing your camera, microphone, and speakers. Please contact your admin for help', PERMISSIONS_NAMESPACE, )(), callback, details, ); case Permissions.LOCATION: return handleSessionPermissions( permissions.geolocation, i18n.t( 'Your administrator has disabled sharing your location. Please contact your admin for help', PERMISSIONS_NAMESPACE, )(), callback, ); case Permissions.NOTIFICATIONS: return handleSessionPermissions( permissions.notifications, i18n.t( 'Your administrator has disabled notifications. Please contact your admin for help', PERMISSIONS_NAMESPACE, )(), callback, ); case Permissions.MIDI_SYSEX: return handleSessionPermissions( permissions.midiSysex, i18n.t( 'Your administrator has disabled MIDI Sysex. Please contact your admin for help', PERMISSIONS_NAMESPACE, )(), callback, ); case Permissions.POINTER_LOCK: return handleSessionPermissions( permissions.pointerLock, i18n.t( 'Your administrator has disabled Pointer Lock. Please contact your admin for help', PERMISSIONS_NAMESPACE, )(), callback, ); case Permissions.FULL_SCREEN: return handleSessionPermissions( permissions.fullscreen, i18n.t( 'Your administrator has disabled Full Screen. Please contact your admin for help', PERMISSIONS_NAMESPACE, )(), callback, ); case Permissions.OPEN_EXTERNAL: if ( details?.externalURL?.startsWith('symphony:') || details?.externalURL?.startsWith('mailto:') ) { return callback(true); } return handleSessionPermissions( permissions.openExternal, i18n.t( 'Your administrator has disabled Opening External App. Please contact your admin for help', PERMISSIONS_NAMESPACE, )(), callback, ); default: return callback(false); } }, ); }; /** * Writes renderer logs to log file * @param _event * @param level * @param message * @param _line * @param _sourceId */ export const onConsoleMessages = (_event, level, message, _line, _sourceId) => { if (level === 0) { logger.log('error', `renderer: ${message}`, [], false); } else if (level === 1) { logger.log('info', `renderer: ${message}`, [], false); } else if (level === 2) { logger.log('warn', `renderer: ${message}`, [], false); } else if (level === 3) { logger.log('error', `renderer: ${message}`, [], false); } else { logger.log('info', `renderer: ${message}`, [], false); } }; /** * Unregisters renderer logs from all the available browser window */ export const unregisterConsoleMessages = () => { const browserWindows = BrowserWindow.getAllWindows(); for (const browserWindow of browserWindows) { if (!browserWindow || !windowExists(browserWindow)) { return; } browserWindow.webContents.removeListener( 'console-message', onConsoleMessages, ); } }; /** * registers renderer logs from all the available browser window */ export const registerConsoleMessages = () => { const browserWindows = BrowserWindow.getAllWindows(); for (const browserWindow of browserWindows) { if (!browserWindow || !windowExists(browserWindow)) { return; } browserWindow.webContents.on('console-message', onConsoleMessages); } };
apache-2.0
Love667767/VideoOnDemand
framework/src/main/java/com/framework/view/tagview/TagGroup.java
39650
package com.framework.view.tagview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.graphics.Rect; import android.graphics.RectF; import android.os.Parcel; import android.os.Parcelable; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.ArrowKeyMovementMethod; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputConnectionWrapper; import android.widget.TextView; import com.framework.R; import java.util.ArrayList; import java.util.List; public class TagGroup extends ViewGroup { private final int default_border_color = Color.rgb(0x49, 0xC1, 0x20); private final int default_text_color = Color.rgb(0x49, 0xC1, 0x20); private final int default_background_color = Color.WHITE; private final int default_dash_border_color = Color.rgb(0xAA, 0xAA, 0xAA); private final int default_input_hint_color = Color.argb(0x80, 0x00, 0x00, 0x00); private final int default_input_text_color = Color.argb(0xDE, 0x00, 0x00, 0x00); private final int default_checked_border_color = Color.rgb(0x49, 0xC1, 0x20); private final int default_checked_text_color = Color.WHITE; private final int default_checked_marker_color = Color.WHITE; private final int default_checked_background_color = Color.rgb(0x49, 0xC1, 0x20); private final int default_pressed_background_color = Color.rgb(0xED, 0xED, 0xED); private final float default_border_stroke_width; private final float default_text_size; private final float default_horizontal_spacing; private final float default_vertical_spacing; private final float default_horizontal_padding; private final float default_vertical_padding; /** Indicates whether this TagGroup is set up to APPEND mode or DISPLAY mode. Default is false. */ private boolean isAppendMode; /** The text to be displayed when the text of the INPUT tag is empty. */ private CharSequence inputHint; /** The tag outline border color. */ private int borderColor; /** The tag text color. */ private int textColor; /** The tag background color. */ private int backgroundColor; /** The dash outline border color. */ private int dashBorderColor; /** The input tag hint text color. */ private int inputHintColor; /** The input tag type text color. */ private int inputTextColor; /** The checked tag outline border color. */ private int checkedBorderColor; /** The check text color */ private int checkedTextColor; /** The checked marker color. */ private int checkedMarkerColor; /** The checked tag background color. */ private int checkedBackgroundColor; /** The tag background color, when the tag is being pressed. */ private int pressedBackgroundColor; /** The tag outline border stroke width, default is 0.5dp. */ private float borderStrokeWidth; /** The tag text size, default is 13sp. */ private float textSize; /** The horizontal tag spacing, default is 8.0dp. */ private int horizontalSpacing; /** The vertical tag spacing, default is 4.0dp. */ private int verticalSpacing; /** The horizontal tag padding, default is 12.0dp. */ private int horizontalPadding; /** The vertical tag padding, default is 3.0dp. */ private int verticalPadding; /** Listener used to dispatch tag change event. */ private OnTagChangeListener mOnTagChangeListener; /** Listener used to dispatch tag click event. */ private OnTagClickListener mOnTagClickListener; /** Listener used to handle tag click event. */ private InternalTagClickListener mInternalTagClickListener = new InternalTagClickListener(); private List<TagView> checkedTagView = new ArrayList<>(); public TagGroup(Context context) { this(context, null); } public TagGroup(Context context, AttributeSet attrs) { this(context, attrs, R.attr.tagGroupStyle); } public TagGroup(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); default_border_stroke_width = dp2px(0.5f); default_text_size = sp2px(13.0f); default_horizontal_spacing = dp2px(8.0f); default_vertical_spacing = dp2px(4.0f); default_horizontal_padding = dp2px(12.0f); default_vertical_padding = dp2px(3.0f); // Load styled attributes. final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TagGroup, defStyleAttr, R.style.TagGroup); try { isAppendMode = a.getBoolean(R.styleable.TagGroup_atg_isAppendMode, false); inputHint = a.getText(R.styleable.TagGroup_atg_inputHint); borderColor = a.getColor(R.styleable.TagGroup_atg_borderColor, default_border_color); textColor = a.getColor(R.styleable.TagGroup_atg_textColor, default_text_color); backgroundColor = a.getColor(R.styleable.TagGroup_atg_backgroundColor, default_background_color); dashBorderColor = a.getColor(R.styleable.TagGroup_atg_dashBorderColor, default_dash_border_color); inputHintColor = a.getColor(R.styleable.TagGroup_atg_inputHintColor, default_input_hint_color); inputTextColor = a.getColor(R.styleable.TagGroup_atg_inputTextColor, default_input_text_color); checkedBorderColor = a.getColor(R.styleable.TagGroup_atg_checkedBorderColor, default_checked_border_color); checkedTextColor = a.getColor(R.styleable.TagGroup_atg_checkedTextColor, default_checked_text_color); checkedMarkerColor = a.getColor(R.styleable.TagGroup_atg_checkedMarkerColor, default_checked_marker_color); checkedBackgroundColor = a.getColor(R.styleable.TagGroup_atg_checkedBackgroundColor, default_checked_background_color); pressedBackgroundColor = a.getColor(R.styleable.TagGroup_atg_pressedBackgroundColor, default_pressed_background_color); borderStrokeWidth = a.getDimension(R.styleable.TagGroup_atg_borderStrokeWidth, default_border_stroke_width); textSize = a.getDimension(R.styleable.TagGroup_atg_textSize, default_text_size); horizontalSpacing = (int) a.getDimension(R.styleable.TagGroup_atg_horizontalSpacing, default_horizontal_spacing); verticalSpacing = (int) a.getDimension(R.styleable.TagGroup_atg_verticalSpacing, default_vertical_spacing); horizontalPadding = (int) a.getDimension(R.styleable.TagGroup_atg_horizontalPadding, default_horizontal_padding); verticalPadding = (int) a.getDimension(R.styleable.TagGroup_atg_verticalPadding, default_vertical_padding); } finally { a.recycle(); } if (isAppendMode) { // Append the initial INPUT tag. //appendInputTag(); // Set the click listener to detect the end-input event. setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { submitTag(); } }); } } /** * Call this to submit the INPUT tag. */ public void submitTag() { final TagView inputTag = getInputTag(); if (inputTag != null && inputTag.isInputAvailable()) { inputTag.endInput(); if (mOnTagChangeListener != null) { mOnTagChangeListener.onAppend(TagGroup.this, inputTag.getText().toString()); } appendInputTag(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); int width = 0; int height = 0; int row = 0; // The row counter. int rowWidth = 0; // Calc the current row width. int rowMaxHeight = 0; // Calc the max tag height, in current row. final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); if (child.getVisibility() != GONE) { rowWidth += childWidth; if (rowWidth > widthSize) { // Next line. rowWidth = childWidth; // The next row width. height += rowMaxHeight + verticalSpacing; rowMaxHeight = childHeight; // The next row max height. row++; } else { // This line. rowMaxHeight = Math.max(rowMaxHeight, childHeight); } rowWidth += horizontalSpacing; } } // Account for the last row height. height += rowMaxHeight; // Account for the padding too. height += getPaddingTop() + getPaddingBottom(); // If the tags grouped in one row, set the width to wrap the tags. if (row == 0) { width = rowWidth; width += getPaddingLeft() + getPaddingRight(); } else {// If the tags grouped exceed one line, set the width to match the parent. width = widthSize; } setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width, heightMode == MeasureSpec.EXACTLY ? heightSize : height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int parentLeft = getPaddingLeft(); final int parentRight = r - l - getPaddingRight(); final int parentTop = getPaddingTop(); final int parentBottom = b - t - getPaddingBottom(); int childLeft = parentLeft; int childTop = parentTop; int rowMaxHeight = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); final int width = child.getMeasuredWidth(); final int height = child.getMeasuredHeight(); if (child.getVisibility() != GONE) { if (childLeft + width > parentRight) { // Next line childLeft = parentLeft; childTop += rowMaxHeight + verticalSpacing; rowMaxHeight = height; } else { rowMaxHeight = Math.max(rowMaxHeight, height); } child.layout(childLeft, childTop, childLeft + width, childTop + height); childLeft += width + horizontalSpacing; } } } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.tags = getTags(); ss.checkedPosition = getCheckedTagIndex(); if (getInputTag() != null) { ss.input = getInputTag().getText().toString(); } return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setTags(ss.tags); TagView checkedTagView = getTagAt(ss.checkedPosition); if (checkedTagView != null) { checkedTagView.setChecked(true); } if (getInputTag() != null) { getInputTag().setText(ss.input); } } /** * Returns the INPUT tag view in this group. * * @return the INPUT state tag view or null if not exists */ protected TagView getInputTag() { if (isAppendMode) { final int inputTagIndex = getChildCount() - 1; final TagView inputTag = getTagAt(inputTagIndex); if (inputTag != null && inputTag.mState == TagView.STATE_INPUT) { return inputTag; } else { return null; } } else { return null; } } /** * Returns the INPUT state tag in this group. * * @return the INPUT state tag view or null if not exists */ public String getInputTagText() { final TagView inputTagView = getInputTag(); if (inputTagView != null) { return inputTagView.getText().toString(); } return null; } /** * Return the last NORMAL state tag view in this group. * * @return the last NORMAL state tag view or null if not exists */ protected TagView getLastNormalTagView() { final int lastNormalTagIndex = isAppendMode ? getChildCount() - 2 : getChildCount() - 1; TagView lastNormalTagView = getTagAt(lastNormalTagIndex); return lastNormalTagView; } /** * Returns the tag array in group, except the INPUT tag. * * @return the tag array. */ public String[] getTags() { final int count = getChildCount(); final List<String> tagList = new ArrayList<>(); for (int i = 0; i < count; i++) { final TagView tagView = getTagAt(i); if (tagView.mState == TagView.STATE_NORMAL) { tagList.add(tagView.getText().toString()); } } return tagList.toArray(new String[tagList.size()]); } /** * @see #setTags(String...) */ public void setTags(List<String> tagList) { setTags(tagList.toArray(new String[tagList.size()])); } /** * Set the tags. It will remove all previous tags first. * * @param tags the tag list to set. */ public void setTags(String... tags) { removeAllViews(); int i = 0; for (final String tag : tags) { appendTag(tag, i); i++; } if (isAppendMode) { //appendInputTag(); } } /** * Returns the tag view at the specified position in the group. * * @param index the position at which to get the tag view from. * @return the tag view at the specified position or null if the position * does not exists within this group. */ public TagView getTagAt(int index) { return (TagView) getChildAt(index); } public List<TagView> getTagsView() { checkedTagView.clear(); final int count = getChildCount(); for (int i = 0; i < count; i++) { final TagView tag = getTagAt(i); checkedTagView.add(tag); } return checkedTagView; } /** * Returns the checked tag view in the group. * * @return the checked tag view or null if not exists. */ protected TagView getCheckedTag() { final int checkedTagIndex = getCheckedTagIndex(); if (checkedTagIndex != -1) { return getTagAt(checkedTagIndex); } return null; } /** * Return the checked tag index. * * @return the checked tag index, or -1 if not exists. */ protected int getCheckedTagIndex() { final int count = getChildCount(); for (int i = 0; i < count; i++) { final TagView tag = getTagAt(i); if (tag.isChecked) { return i; } } return -1; } public Integer[] getCheckedTags() { List<Integer> tagIndexs = new ArrayList<>(); final int count = getChildCount(); for (int i = 0; i < count; i++) { final TagView tag = getTagAt(i); if (tag.isChecked) { tagIndexs.add(i); } } return tagIndexs.toArray(new Integer[tagIndexs.size()]); } public int getFirstCheckTagIndex() { final int count = getChildCount(); for (int i = 0; i < count; i++) { final TagView tag = getTagAt(i); if (tag.isChecked) { return i; } } return -1; } /** * Register a callback to be invoked when this tag group is changed. * * @param l the callback that will run */ public void setOnTagChangeListener(OnTagChangeListener l) { mOnTagChangeListener = l; } public void setAppendMode(boolean appendMode) { isAppendMode = appendMode; } /** * @see #appendInputTag(String) */ protected void appendInputTag() { appendInputTag(null); } /** * Append a INPUT tag to this group. It will throw an exception if there has a previous INPUT tag. * * @param tag the tag text. */ protected void appendInputTag(String tag) { final TagView previousInputTag = getInputTag(); if (previousInputTag != null) { throw new IllegalStateException("Already has a INPUT tag in group."); } final TagView newInputTag = new TagView(getContext(), TagView.STATE_INPUT, tag); newInputTag.setOnClickListener(mInternalTagClickListener); addView(newInputTag); } /** * Append tag to this group. * * @param tag the tag to append. */ protected void appendTag(CharSequence tag, int position) { final TagView newTag = new TagView(getContext(), TagView.STATE_NORMAL, tag, position); newTag.setOnClickListener(mInternalTagClickListener); addView(newTag); } public float dp2px(float dp) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); } public float sp2px(float sp) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics()); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } /** * Register a callback to be invoked when a tag is clicked. * * @param l the callback that will run. */ public void setOnTagClickListener(OnTagClickListener l) { mOnTagClickListener = l; } protected void deleteTag(TagView tagView) { removeView(tagView); if (mOnTagChangeListener != null) { mOnTagChangeListener.onDelete(TagGroup.this, tagView.getText().toString()); } } /** * Interface definition for a callback to be invoked when a tag group is changed. */ public interface OnTagChangeListener { /** * Called when a tag has been appended to the group. * * @param tag the appended tag. */ void onAppend(TagGroup tagGroup, String tag); /** * Called when a tag has been deleted from the the group. * * @param tag the deleted tag. */ void onDelete(TagGroup tagGroup, String tag); } /** * Interface definition for a callback to be invoked when a tag is clicked. */ public interface OnTagClickListener { /** * Called when a tag has been clicked. * * @param tag The tag text of the tag that was clicked. */ void onTagClick(TagView tag); void unTagClick(TagView tag); } /** * Per-child layout information for layouts. */ public static class LayoutParams extends ViewGroup.LayoutParams { public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); } } /** * For {@link TagGroup} save and restore state. */ static class SavedState extends BaseSavedState { public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; int tagCount; String[] tags; int checkedPosition; String input; public SavedState(Parcel source) { super(source); tagCount = source.readInt(); tags = new String[tagCount]; source.readStringArray(tags); checkedPosition = source.readInt(); input = source.readString(); } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); tagCount = tags.length; dest.writeInt(tagCount); dest.writeStringArray(tags); dest.writeInt(checkedPosition); dest.writeString(input); } } /** * The tag view click listener for internal use. */ class InternalTagClickListener implements OnClickListener { @Override public void onClick(View v) { final TagView tag = (TagView) v; if (isAppendMode) { if (tag.mState == TagView.STATE_INPUT) { // If the clicked tag is in INPUT state, uncheck the previous checked tag if exists. final TagView checkedTag = getCheckedTag(); if (checkedTag != null) { checkedTag.setChecked(false); } } else { // If the clicked tag is currently checked, delete the tag. if (tag.isChecked) { tag.setChecked(false); //deleteTag(tag); if (mOnTagClickListener != null) { mOnTagClickListener.unTagClick(tag); } } else { // If the clicked tag is unchecked, uncheck the previous checked tag if exists, // then check the clicked tag. final TagView checkedTag = getCheckedTag(); if (checkedTag != null) { //checkedTag.setChecked(false); } tag.setChecked(true); if (mOnTagClickListener != null) { mOnTagClickListener.onTagClick(tag); } } } } else { if (mOnTagClickListener != null) { mOnTagClickListener.onTagClick(tag); } } } } /** * The tag view which has two states can be either NORMAL or INPUT. */ public class TagView extends TextView { public static final int STATE_NORMAL = 1; public static final int STATE_INPUT = 2; /** The offset to the text. */ private static final int CHECKED_MARKER_OFFSET = 3; /** The stroke width of the checked marker */ private static final int CHECKED_MARKER_STROKE_WIDTH = 4; /** The current state. */ private int mState; /** Indicates the tag if checked. */ private boolean isChecked = false; /** Indicates the tag if pressed. */ private boolean isPressed = false; private Paint mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint mCheckedMarkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); /** The rect for the tag's left corner drawing. */ private RectF mLeftCornerRectF = new RectF(); /** The rect for the tag's right corner drawing. */ private RectF mRightCornerRectF = new RectF(); /** The rect for the tag's horizontal blank fill area. */ private RectF mHorizontalBlankFillRectF = new RectF(); /** The rect for the tag's vertical blank fill area. */ private RectF mVerticalBlankFillRectF = new RectF(); /** The rect for the checked mark draw bound. */ private RectF mCheckedMarkerBound = new RectF(); /** Used to detect the touch event. */ private Rect mOutRect = new Rect(); /** The path for draw the tag's outline border. */ private Path mBorderPath = new Path(); private int position; /** The path effect provide draw the dash border. */ private PathEffect mPathEffect = new DashPathEffect(new float[]{10, 5}, 0); { mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setStrokeWidth(borderStrokeWidth); mBackgroundPaint.setStyle(Paint.Style.FILL); mCheckedMarkerPaint.setStyle(Paint.Style.FILL); mCheckedMarkerPaint.setStrokeWidth(CHECKED_MARKER_STROKE_WIDTH); mCheckedMarkerPaint.setColor(checkedMarkerColor); } public int getPosition() { return position; } public TagView(Context context, final int state, CharSequence text) { this(context, state, text, -1); } public TagView(Context context, final int state, CharSequence text, int position) { super(context); this.position = position; setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding); setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); setGravity(Gravity.CENTER); setText(text); setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); mState = state; setClickable(true); setFocusable(state == STATE_INPUT); setFocusableInTouchMode(state == STATE_INPUT); setHint(state == STATE_INPUT ? inputHint : null); setMovementMethod(state == STATE_INPUT ? ArrowKeyMovementMethod.getInstance() : null); // Interrupted long click event to avoid PAUSE popup. setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { return state != STATE_INPUT; } }); if (state == STATE_INPUT) { requestFocus(); // Handle the ENTER key down. setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_NULL && (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) { if (isInputAvailable()) { // If the input content is available, end the input and dispatch // the event, then append a new INPUT state tag. endInput(); if (mOnTagChangeListener != null) { mOnTagChangeListener.onAppend(TagGroup.this, getText().toString()); } appendInputTag(); } return true; } return false; } }); // Handle the BACKSPACE key down. setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) { // If the input content is empty, check or remove the last NORMAL state tag. if (TextUtils.isEmpty(getText().toString())) { TagView lastNormalTagView = getLastNormalTagView(); if (lastNormalTagView != null) { if (lastNormalTagView.isChecked) { removeView(lastNormalTagView); if (mOnTagChangeListener != null) { mOnTagChangeListener.onDelete(TagGroup.this, lastNormalTagView.getText().toString()); } } else { final TagView checkedTagView = getCheckedTag(); if (checkedTagView != null) { checkedTagView.setChecked(false); } lastNormalTagView.setChecked(true); } return true; } } } return false; } }); // Handle the INPUT tag content changed. addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // When the INPUT state tag changed, uncheck the checked tag if exists. final TagView checkedTagView = getCheckedTag(); if (checkedTagView != null) { checkedTagView.setChecked(false); } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); } invalidatePaint(); } /** * Set whether this tag view is in the checked state. * * @param checked true is checked, false otherwise */ public void setChecked(boolean checked) { isChecked = checked; // Make the checked mark drawing region. setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding); invalidatePaint(); } public boolean isChecked() { return isChecked; } /** * Call this method to end this tag's INPUT state. */ public void endInput() { // Make the view not focusable. setFocusable(false); setFocusableInTouchMode(false); // Set the hint empty, make the TextView measure correctly. setHint(null); // Take away the cursor. setMovementMethod(null); mState = STATE_NORMAL; invalidatePaint(); requestLayout(); } @Override protected boolean getDefaultEditable() { return true; } /** * Indicates whether the input content is available. * * @return True if the input content is available, false otherwise. */ public boolean isInputAvailable() { return getText() != null && getText().length() > 0; } private void invalidatePaint() { if (isAppendMode) { if (mState == STATE_INPUT) { mBorderPaint.setColor(dashBorderColor); mBorderPaint.setPathEffect(mPathEffect); mBackgroundPaint.setColor(backgroundColor); setHintTextColor(inputHintColor); setTextColor(inputTextColor); } else { mBorderPaint.setPathEffect(null); if (isChecked) { mBorderPaint.setColor(checkedBorderColor); mBackgroundPaint.setColor(checkedBackgroundColor); setTextColor(checkedTextColor); } else { mBorderPaint.setColor(borderColor); mBackgroundPaint.setColor(backgroundColor); setTextColor(textColor); } } } else { mBorderPaint.setColor(borderColor); mBackgroundPaint.setColor(backgroundColor); setTextColor(textColor); } if (isPressed) { mBackgroundPaint.setColor(pressedBackgroundColor); } } @Override protected void onDraw(Canvas canvas) { canvas.drawArc(mLeftCornerRectF, -180, 90, true, mBackgroundPaint); canvas.drawArc(mLeftCornerRectF, -270, 90, true, mBackgroundPaint); canvas.drawArc(mRightCornerRectF, -90, 90, true, mBackgroundPaint); canvas.drawArc(mRightCornerRectF, 0, 90, true, mBackgroundPaint); canvas.drawRect(mHorizontalBlankFillRectF, mBackgroundPaint); canvas.drawRect(mVerticalBlankFillRectF, mBackgroundPaint); if (isChecked) { /* canvas.save(); canvas.rotate(45, mCheckedMarkerBound.centerX(), mCheckedMarkerBound.centerY()); canvas.drawLine(mCheckedMarkerBound.left, mCheckedMarkerBound.centerY(), mCheckedMarkerBound.right, mCheckedMarkerBound.centerY(), mCheckedMarkerPaint); canvas.drawLine(mCheckedMarkerBound.centerX(), mCheckedMarkerBound.top, mCheckedMarkerBound.centerX(), mCheckedMarkerBound.bottom, mCheckedMarkerPaint); canvas.restore(); */ } canvas.drawPath(mBorderPath, mBorderPaint); super.onDraw(canvas); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int left = (int) borderStrokeWidth; int top = (int) borderStrokeWidth; int right = (int) (left + w - borderStrokeWidth * 2); int bottom = (int) (top + h - borderStrokeWidth * 2); int d = bottom - top; mLeftCornerRectF.set(left, top, left + d, top + d); mRightCornerRectF.set(right - d, top, right, top + d); mBorderPath.reset(); mBorderPath.addArc(mLeftCornerRectF, -180, 90); mBorderPath.addArc(mLeftCornerRectF, -270, 90); mBorderPath.addArc(mRightCornerRectF, -90, 90); mBorderPath.addArc(mRightCornerRectF, 0, 90); int l = (int) (d / 2.0f); mBorderPath.moveTo(left + l, top); mBorderPath.lineTo(right - l, top); mBorderPath.moveTo(left + l, bottom); mBorderPath.lineTo(right - l, bottom); mBorderPath.moveTo(left, top + l); mBorderPath.lineTo(left, bottom - l); mBorderPath.moveTo(right, top + l); mBorderPath.lineTo(right, bottom - l); mHorizontalBlankFillRectF.set(left, top + l, right, bottom - l); mVerticalBlankFillRectF.set(left + l, top, right - l, bottom); int m = (int) (h / 2.5f); h = bottom - top; mCheckedMarkerBound.set(right - m - horizontalPadding + CHECKED_MARKER_OFFSET, top + h / 2 - m / 2, right - horizontalPadding + CHECKED_MARKER_OFFSET, bottom - h / 2 + m / 2); // Ensure the checked mark drawing region is correct across screen orientation changes. if (isChecked) { // setPadding(horizontalPadding, // verticalPadding, // (int) (horizontalPadding + h / 2.5f + CHECKED_MARKER_OFFSET), // verticalPadding); } } @Override public boolean onTouchEvent(MotionEvent event) { if (mState == STATE_INPUT) { // The INPUT tag doesn't change background color on the touch event. return super.onTouchEvent(event); } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { getDrawingRect(mOutRect); isPressed = true; invalidatePaint(); invalidate(); break; } case MotionEvent.ACTION_MOVE: { if (!mOutRect.contains((int) event.getX(), (int) event.getY())) { isPressed = false; invalidatePaint(); invalidate(); } break; } case MotionEvent.ACTION_UP: { isPressed = false; invalidatePaint(); invalidate(); break; } } return super.onTouchEvent(event); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return new ZanyInputConnection(super.onCreateInputConnection(outAttrs), true); } /** * Solve edit text delete(backspace) key detect, see<a href="http://stackoverflow.com/a/14561345/3790554"> * Android: Backspace in WebView/BaseInputConnection</a> */ private class ZanyInputConnection extends InputConnectionWrapper { public ZanyInputConnection(InputConnection target, boolean mutable) { super(target, mutable); } @Override public boolean deleteSurroundingText(int beforeLength, int afterLength) { // magic: in latest Android, deleteSurroundingText(1, 0) will be called for backspace if (beforeLength == 1 && afterLength == 0) { // backspace return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL)); } return super.deleteSurroundingText(beforeLength, afterLength); } } } }
apache-2.0
azachar/eclipse-plugin-cleaner
src/main/java/eu/chocolatejar/eclipse/plugin/cleaner/util/DropinsFilter.java
1522
/******************************************************************************* * Copyright 2014 Chocolate Jar, Andrej Zachar * * 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 eu.chocolatejar.eclipse.plugin.cleaner.util; import java.io.File; import java.io.FileFilter; import java.util.regex.Pattern; /** * Filters only file(s) within the dropins folder. */ public class DropinsFilter implements FileFilter { /** * Name for the Eclipse dropins folder */ public static final String DROPINS = "dropins"; private static final String SLASH = "\\" + File.separator; private static final Pattern DROPINS_FOLDER_PATTERN = Pattern.compile("(" + SLASH + "?(" + DROPINS + SLASH + "){1})+"); @Override public boolean accept(File file) { if (file == null) { return false; } return DROPINS_FOLDER_PATTERN.matcher(file.getAbsolutePath()).find(); } }
apache-2.0
gfawcett22/EnterprisePlanner
App/src/app/table/thead/rows/thead-filters-row.component.ts
992
import { FilterObject } from '../../lib/interfaces/FilterObject'; import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { Grid } from '../../lib/grid'; import { Column } from "../../lib/column"; @Component({ selector: '[thead-filters-row]', template: ` <th *ngIf="grid.getSetting('showActionButtons')"> <button md-raised-button (click)="create.emit(null)">Create New</button> </th> <th *ngFor="let column of grid.getColumns()" > <table-filter [column]="column" (filter)="updateFilters($event)"> </table-filter> </th> `, }) export class TheadFitlersRowComponent { @Input() grid: Grid; @Output() create = new EventEmitter<any>(); @Output() filter = new EventEmitter<any>(); private filterObject: Object = {}; updateFilters($event: Object): void { if ($event) { Object.assign(this.filterObject, $event); this.filter.emit(this.filterObject); } } }
apache-2.0
userzimmermann/robotframework
utest/utils/test_xmlwriter.py
6078
from six import PY3 import os import unittest import tempfile from robot.utils import XmlWriter, ET, ETSource from robot.utils.asserts import * PATH = os.path.join(tempfile.gettempdir(), 'test_xmlwriter.xml') class TestXmlWriter(unittest.TestCase): def setUp(self): self.writer = XmlWriter(PATH) def tearDown(self): self.writer.close() os.remove(PATH) def test_write_element_in_pieces(self): self.writer.start('name', {'attr': 'value'}, newline=False) self.writer.content('Some content here!!') self.writer.end('name') self._verify_node(None, 'name', 'Some content here!!', {'attr': 'value'}) def test_calling_content_multiple_times(self): self.writer.start(u'robot-log', newline=False) self.writer.content(u'Hello world!\n') self.writer.content(u'Hi again!') self.writer.content('\tMy name is John') self.writer.end('robot-log') self._verify_node(None, 'robot-log', 'Hello world!\nHi again!\tMy name is John') def test_write_element(self): self.writer.element('foo', 'Node\n content', {'a1': 'attr1', 'a2': 'attr2'}) self._verify_node(None, 'foo', 'Node\n content', {'a1': 'attr1', 'a2': 'attr2'}) def test_write_many_elements(self): self.writer.start('root', {'version': 'test'}) self.writer.start('child1', {'my-attr': 'my value'}) self.writer.element('leaf1.1', 'leaf content', {'type': 'kw'}) self.writer.element('leaf1.2') self.writer.end('child1') self.writer.element('child2', attrs={'class': 'foo'}) self.writer.end('root') root = self._get_root() self._verify_node(root, 'root', attrs={'version': 'test'}) self._verify_node(root.find('child1'), 'child1', attrs={'my-attr': 'my value'}) self._verify_node(root.find('child1/leaf1.1'), 'leaf1.1', 'leaf content', {'type': 'kw'}) self._verify_node(root.find('child1/leaf1.2'), 'leaf1.2') self._verify_node(root.find('child2'), 'child2', attrs={'class': 'foo'}) def test_newline_insertion(self): self.writer.start('root') self.writer.start('suite', {'type': 'directory_suite'}) self.writer.element('test', attrs={'name': 'my_test'}, newline=False) self.writer.element('test', attrs={'name': 'my_2nd_test'}) self.writer.end('suite', False) self.writer.start('suite', {'name': 'another suite'}, newline=False) self.writer.content('Suite 2 content') self.writer.end('suite') self.writer.end('root') content = self._get_content() lines = [line for line in content.splitlines() if line != '\n'] assert_equal(len(lines), 6) def test_none_content(self): self.writer.element(u'robot-log', None) self._verify_node(None, 'robot-log') def test_none_and_empty_attrs(self): self.writer.element('foo', attrs={'empty': '', 'none': None}) self._verify_node(None, 'foo', attrs={'empty': '', 'none': ''}) def test_content_with_invalid_command_char(self): self.writer.element('robot-log', '\033[31m\033[32m\033[33m\033[m') self._verify_node(None, 'robot-log', '[31m[32m[33m[m') def test_content_with_invalid_command_char_unicode(self): self.writer.element('robot-log', u'\x1b[31m\x1b[32m\x1b[33m\x1b[m') self._verify_node(None, 'robot-log', '[31m[32m[33m[m') def test_content_with_non_ascii(self): self.writer.start('root') self.writer.element(u'e', u'Circle is 360\xB0') self.writer.element(u'f', u'Hyv\xE4\xE4 \xFC\xF6t\xE4') self.writer.end('root') root = self._get_root() self._verify_node(root.find('e'), 'e', u'Circle is 360\xB0') self._verify_node(root.find('f'), 'f', u'Hyv\xE4\xE4 \xFC\xF6t\xE4') def test_content_with_entities(self): self.writer.element(u'robot-log', 'Me, Myself & I > you') self._verify_content('Me, Myself &amp; I &gt; you') def test_remove_illegal_chars(self): assert_equals(self.writer._escape(u'\x1b[31m'), '[31m') assert_equals(self.writer._escape(u'\x00'), '') def test_ioerror_when_file_is_invalid(self): assert_raises(IOError, XmlWriter, os.path.dirname(__file__)) def test_custom_encoding(self): encoding='ISO-8859-1' self.writer.close() self.writer = XmlWriter(PATH, encoding=encoding) self.writer.element('test', u'hyv\xe4') self._verify_content('encoding="ISO-8859-1"', encoding=encoding) self._verify_node(None, 'test', u'hyv\xe4') def test_dont_write_empty(self): self.tearDown() class NoPreamble(XmlWriter): def _preamble(self): pass self.writer = NoPreamble(PATH, write_empty=False) self.writer.element('foo1', content='', attrs={}) self.writer.element('foo2', attrs={'bar': '', 'None': None}) self.writer.element('foo3', attrs={'bar': '', 'value': 'value'}) assert_equals(self._get_content(), '<foo3 value="value"></foo3>\n') def _verify_node(self, node, name, text=None, attrs={}): if node is None: node = self._get_root() assert_equals(node.tag, name) if text is not None: assert_equals(node.text, text) assert_equals(node.attrib, attrs) def _verify_content(self, expected, encoding='UTF-8'): content = self._get_content(encoding) assert_true(expected in content, 'Failed to find:\n%s\n\nfrom:\n%s' % (expected, content)) def _get_root(self): self.writer.close() with ETSource(PATH) as source: return ET.parse(source).getroot() def _get_content(self, encoding='UTF-8'): self.writer.close() with open(PATH, encoding=encoding) if PY3 else open(PATH) as f: return f.read() if __name__ == '__main__': unittest.main()
apache-2.0
MaYunFei/TXLiveDemo
livesocketlib/src/main/java/com/dongao/kaoqian/livesocketlib/message/MessageFactory.java
3619
package com.dongao.kaoqian.livesocketlib.message; import android.util.Log; import com.alibaba.fastjson.JSON; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.util.zip.DataFormatException; import java.util.zip.Inflater; /** * 消息种类 * Created by mayunfei on 17-9-18. */ public class MessageFactory { private static final String TAG = "MessageFactory"; public static LiveMessage messagePause(String compressMsg) { String msgText = uncompress(compressMsg); Log.i(TAG, msgText); try { JSONObject jsonObject = new JSONObject(msgText); String type = jsonObject.optString("type"); JSONObject data = jsonObject.optJSONObject("data"); if (data == null) { return null; } switch (type) { case LiveMessage.TYPE_DRAW: String method = data.getString("method"); switch (method) { case LiveMessage.METHOD_LINE: return JSON.parseObject(msgText, DrawLineMessage.class); case LiveMessage.METHOD_ELLIPSE: return JSON.parseObject(msgText, DrawEllipseMessage.class); case LiveMessage.METHOD_RECT: return JSON.parseObject(msgText, DrawRectMessage.class); case LiveMessage.METHOD_ERASE: return JSON.parseObject(msgText, DrawEraseMessage.class); case LiveMessage.METHOD_CLEARALL: return JSON.parseObject(msgText, DrawClearMessage.class); case LiveMessage.METHOD_TEXT: case LiveMessage.METHOD_TEXT_SAVE: return JSON.parseObject(msgText, DrawTextMessage.class); case LiveMessage.METHOD_ARROW: return JSON.parseObject(msgText, DrawArrowMessage.class); } break; case LiveMessage.TYPE_PPT_CHANGE: return JSON.parseObject(msgText, ChangePPTMessage.class); case LiveMessage.TYPE_CLASS_BEGIN: return JSON.parseObject(msgText, ClassBeginMessage.class); case LiveMessage.TYPE_CLASS_REST: return JSON.parseObject(msgText, ClassRestMessage.class); } return null; } catch (JSONException e) { e.printStackTrace(); } return null; } /** * 解压数据 */ private static String uncompress(String str) { Inflater decompressor = new Inflater(); ByteArrayOutputStream bos = null; byte[] value = null; try { value = str.getBytes("ISO-8859-1"); bos = new ByteArrayOutputStream(value.length); decompressor.setInput(value); final byte[] buf = new byte[1024]; while (!decompressor.finished()) { int count = 0; count = decompressor.inflate(buf); bos.write(buf, 0, count); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DataFormatException e) { e.printStackTrace(); } finally { decompressor.end(); } if (bos != null) { return bos.toString(); } return null; } }
apache-2.0
pcmoritz/arrow
csharp/src/Apache.Arrow/Flatbuf/Enums/Precision.cs
223
// <auto-generated> // automatically generated by the FlatBuffers compiler, do not modify // </auto-generated> namespace Apache.Arrow.Flatbuf { public enum Precision : short { HALF = 0, SINGLE = 1, DOUBLE = 2, }; }
apache-2.0
sindharta/unity-sandbox
UnitySandboxMLAPI/Packages/com.unity.multiplayer.mlapi/Runtime/NetworkVariable/NetworkVariable.cs
19592
using System.Collections.Generic; using UnityEngine; using System.IO; using System; using MLAPI.Serialization.Pooled; using MLAPI.Transports; namespace MLAPI.NetworkVariable { /// <summary> /// A variable that can be synchronized over the network. /// </summary> [Serializable] public class NetworkVariable<T> : INetworkVariable { /// <summary> /// The settings for this var /// </summary> public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); /// <summary> /// The last time the variable was written to locally /// </summary> public ushort LocalTick { get; internal set; } /// <summary> /// The last time the variable was written to remotely. Uses the remote timescale /// </summary> public ushort RemoteTick { get; internal set; } /// <summary> /// Delegate type for value changed event /// </summary> /// <param name="previousValue">The value before the change</param> /// <param name="newValue">The new value</param> public delegate void OnValueChangedDelegate(T previousValue, T newValue); /// <summary> /// The callback to be invoked when the value gets changed /// </summary> public OnValueChangedDelegate OnValueChanged; private NetworkBehaviour m_NetworkBehaviour; /// <summary> /// Creates a NetworkVariable with the default value and settings /// </summary> public NetworkVariable() { } /// <summary> /// Creates a NetworkVariable with the default value and custom settings /// </summary> /// <param name="settings">The settings to use for the NetworkVariable</param> public NetworkVariable(NetworkVariableSettings settings) { Settings = settings; } /// <summary> /// Creates a NetworkVariable with a custom value and custom settings /// </summary> /// <param name="settings">The settings to use for the NetworkVariable</param> /// <param name="value">The initial value to use for the NetworkVariable</param> public NetworkVariable(NetworkVariableSettings settings, T value) { Settings = settings; m_InternalValue = value; } /// <summary> /// Creates a NetworkVariable with a custom value and the default settings /// </summary> /// <param name="value">The initial value to use for the NetworkVariable</param> public NetworkVariable(T value) { m_InternalValue = value; } [SerializeField] private T m_InternalValue; /// <summary> /// The value of the NetworkVariable container /// </summary> public T Value { get => m_InternalValue; set { if (EqualityComparer<T>.Default.Equals(m_InternalValue, value)) return; // Setter is assumed to be called locally, by game code. // When used by the host, it is its responsibility to set the RemoteTick RemoteTick = NetworkTickSystem.NoTick; m_IsDirty = true; T previousValue = m_InternalValue; m_InternalValue = value; OnValueChanged?.Invoke(previousValue, m_InternalValue); } } private bool m_IsDirty = false; /// <summary> /// Sets whether or not the variable needs to be delta synced /// </summary> public void SetDirty(bool isDirty) { m_IsDirty = isDirty; } /// <inheritdoc /> public bool IsDirty() { return m_IsDirty; } /// <inheritdoc /> public void ResetDirty() { m_IsDirty = false; } /// <inheritdoc /> public bool CanClientRead(ulong clientId) { switch (Settings.ReadPermission) { case NetworkVariablePermission.Everyone: return true; case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.ReadPermissionCallback == null) return false; return Settings.ReadPermissionCallback(clientId); } } return true; } /// <summary> /// Writes the variable to the writer /// </summary> /// <param name="stream">The stream to write the value to</param> public void WriteDelta(Stream stream) { WriteField(stream); } /// <inheritdoc /> public bool CanClientWrite(ulong clientId) { switch (Settings.WritePermission) { case NetworkVariablePermission.Everyone: return true; case NetworkVariablePermission.ServerOnly: return false; case NetworkVariablePermission.OwnerOnly: return m_NetworkBehaviour.OwnerClientId == clientId; case NetworkVariablePermission.Custom: { if (Settings.WritePermissionCallback == null) return false; return Settings.WritePermissionCallback(clientId); } } return true; } /// <summary> /// Reads value from the reader and applies it /// </summary> /// <param name="stream">The stream to read the value from</param> /// <param name="keepDirtyDelta">Whether or not the container should keep the dirty delta, or mark the delta as consumed</param> public void ReadDelta(Stream stream, bool keepDirtyDelta, ushort localTick, ushort remoteTick) { // todo: This allows the host-returned value to be set back to an old value // this will need to be adjusted to check if we're have a most recent value LocalTick = localTick; RemoteTick = remoteTick; using (var reader = PooledNetworkReader.Get(stream)) { T previousValue = m_InternalValue; m_InternalValue = (T)reader.ReadObjectPacked(typeof(T)); if (keepDirtyDelta) m_IsDirty = true; OnValueChanged?.Invoke(previousValue, m_InternalValue); } } /// <inheritdoc /> public void SetNetworkBehaviour(NetworkBehaviour behaviour) { m_NetworkBehaviour = behaviour; } /// <inheritdoc /> public void ReadField(Stream stream, ushort localTick, ushort remoteTick) { ReadDelta(stream, false, localTick, remoteTick); } /// <inheritdoc /> public void WriteField(Stream stream) { // Store the local tick at which this NetworkVariable was modified LocalTick = NetworkBehaviour.CurrentTick; using (var writer = PooledNetworkWriter.Get(stream)) { writer.WriteObjectPacked(m_InternalValue); //BOX } } /// <inheritdoc /> public NetworkChannel GetChannel() { return Settings.SendNetworkChannel; } } /// <summary> /// A NetworkVariable that holds strings and support serialization /// </summary> [Serializable] public class NetworkVariableString : NetworkVariable<string> { /// <inheritdoc /> public NetworkVariableString() : base(string.Empty) { } /// <inheritdoc /> public NetworkVariableString(NetworkVariableSettings settings) : base(settings, string.Empty) { } /// <inheritdoc /> public NetworkVariableString(string value) : base(value) { } /// <inheritdoc /> public NetworkVariableString(NetworkVariableSettings settings, string value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds bools and support serialization /// </summary> [Serializable] public class NetworkVariableBool : NetworkVariable<bool> { /// <inheritdoc /> public NetworkVariableBool() { } /// <inheritdoc /> public NetworkVariableBool(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableBool(bool value) : base(value) { } /// <inheritdoc /> public NetworkVariableBool(NetworkVariableSettings settings, bool value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds bytes and support serialization /// </summary> [Serializable] public class NetworkVariableByte : NetworkVariable<byte> { /// <inheritdoc /> public NetworkVariableByte() { } /// <inheritdoc /> public NetworkVariableByte(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableByte(byte value) : base(value) { } /// <inheritdoc /> public NetworkVariableByte(NetworkVariableSettings settings, byte value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds sbytes and support serialization /// </summary> [Serializable] public class NetworkVariableSByte : NetworkVariable<sbyte> { /// <inheritdoc /> public NetworkVariableSByte() { } /// <inheritdoc /> public NetworkVariableSByte(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableSByte(sbyte value) : base(value) { } /// <inheritdoc /> public NetworkVariableSByte(NetworkVariableSettings settings, sbyte value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds ushorts and support serialization /// </summary> [Serializable] public class NetworkVariableUShort : NetworkVariable<ushort> { /// <inheritdoc /> public NetworkVariableUShort() { } /// <inheritdoc /> public NetworkVariableUShort(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableUShort(ushort value) : base(value) { } /// <inheritdoc /> public NetworkVariableUShort(NetworkVariableSettings settings, ushort value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds shorts and support serialization /// </summary> [Serializable] public class NetworkVariableShort : NetworkVariable<short> { /// <inheritdoc /> public NetworkVariableShort() { } /// <inheritdoc /> public NetworkVariableShort(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableShort(short value) : base(value) { } /// <inheritdoc /> public NetworkVariableShort(NetworkVariableSettings settings, short value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds uints and support serialization /// </summary> [Serializable] public class NetworkVariableUInt : NetworkVariable<uint> { /// <inheritdoc /> public NetworkVariableUInt() { } /// <inheritdoc /> public NetworkVariableUInt(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableUInt(uint value) : base(value) { } /// <inheritdoc /> public NetworkVariableUInt(NetworkVariableSettings settings, uint value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds ints and support serialization /// </summary> [Serializable] public class NetworkVariableInt : NetworkVariable<int> { /// <inheritdoc /> public NetworkVariableInt() { } /// <inheritdoc /> public NetworkVariableInt(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableInt(int value) : base(value) { } /// <inheritdoc /> public NetworkVariableInt(NetworkVariableSettings settings, int value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds ulongs and support serialization /// </summary> [Serializable] public class NetworkVariableULong : NetworkVariable<ulong> { /// <inheritdoc /> public NetworkVariableULong() { } /// <inheritdoc /> public NetworkVariableULong(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableULong(ulong value) : base(value) { } /// <inheritdoc /> public NetworkVariableULong(NetworkVariableSettings settings, ulong value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds longs and support serialization /// </summary> [Serializable] public class NetworkVariableLong : NetworkVariable<long> { /// <inheritdoc /> public NetworkVariableLong() { } /// <inheritdoc /> public NetworkVariableLong(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableLong(long value) : base(value) { } /// <inheritdoc /> public NetworkVariableLong(NetworkVariableSettings settings, long value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds floats and support serialization /// </summary> [Serializable] public class NetworkVariableFloat : NetworkVariable<float> { /// <inheritdoc /> public NetworkVariableFloat() { } /// <inheritdoc /> public NetworkVariableFloat(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableFloat(float value) : base(value) { } /// <inheritdoc /> public NetworkVariableFloat(NetworkVariableSettings settings, float value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds doubles and support serialization /// </summary> [Serializable] public class NetworkVariableDouble : NetworkVariable<double> { /// <inheritdoc /> public NetworkVariableDouble() { } /// <inheritdoc /> public NetworkVariableDouble(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableDouble(double value) : base(value) { } /// <inheritdoc /> public NetworkVariableDouble(NetworkVariableSettings settings, double value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds vector2s and support serialization /// </summary> [Serializable] public class NetworkVariableVector2 : NetworkVariable<Vector2> { /// <inheritdoc /> public NetworkVariableVector2() { } /// <inheritdoc /> public NetworkVariableVector2(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableVector2(Vector2 value) : base(value) { } /// <inheritdoc /> public NetworkVariableVector2(NetworkVariableSettings settings, Vector2 value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds vector3s and support serialization /// </summary> [Serializable] public class NetworkVariableVector3 : NetworkVariable<Vector3> { /// <inheritdoc /> public NetworkVariableVector3() { } /// <inheritdoc /> public NetworkVariableVector3(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableVector3(Vector3 value) : base(value) { } /// <inheritdoc /> public NetworkVariableVector3(NetworkVariableSettings settings, Vector3 value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds vector4s and support serialization /// </summary> [Serializable] public class NetworkVariableVector4 : NetworkVariable<Vector4> { /// <inheritdoc /> public NetworkVariableVector4() { } /// <inheritdoc /> public NetworkVariableVector4(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableVector4(Vector4 value) : base(value) { } /// <inheritdoc /> public NetworkVariableVector4(NetworkVariableSettings settings, Vector4 value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds colors and support serialization /// </summary> [Serializable] public class NetworkVariableColor : NetworkVariable<Color> { /// <inheritdoc /> public NetworkVariableColor() { } /// <inheritdoc /> public NetworkVariableColor(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableColor(Color value) : base(value) { } /// <inheritdoc /> public NetworkVariableColor(NetworkVariableSettings settings, Color value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds color32s and support serialization /// </summary> [Serializable] public class NetworkVariableColor32 : NetworkVariable<Color32> { /// <inheritdoc /> public NetworkVariableColor32() { } /// <inheritdoc /> public NetworkVariableColor32(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableColor32(Color32 value) : base(value) { } /// <inheritdoc /> public NetworkVariableColor32(NetworkVariableSettings settings, Color32 value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds rays and support serialization /// </summary> [Serializable] public class NetworkVariableRay : NetworkVariable<Ray> { /// <inheritdoc /> public NetworkVariableRay() { } /// <inheritdoc /> public NetworkVariableRay(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableRay(Ray value) : base(value) { } /// <inheritdoc /> public NetworkVariableRay(NetworkVariableSettings settings, Ray value) : base(settings, value) { } } /// <summary> /// A NetworkVariable that holds quaternions and support serialization /// </summary> [Serializable] public class NetworkVariableQuaternion : NetworkVariable<Quaternion> { /// <inheritdoc /> public NetworkVariableQuaternion() { } /// <inheritdoc /> public NetworkVariableQuaternion(NetworkVariableSettings settings) : base(settings) { } /// <inheritdoc /> public NetworkVariableQuaternion(Quaternion value) : base(value) { } /// <inheritdoc /> public NetworkVariableQuaternion(NetworkVariableSettings settings, Quaternion value) : base(settings, value) { } } }
apache-2.0
splicers/elastigo
lib/coremget.go
2044
// Copyright 2013 Matthew Baird // 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 elastigo import ( "encoding/json" "fmt" ) // MGet allows the caller to get multiple documents based on an index, type (optional) and id (and possibly routing). // The response includes a docs array with all the fetched documents, each element similar in structure to a document // provided by the get API. // see http://www.elasticsearch.org/guide/reference/api/multi-get.html func (c *Conn) MGet(index string, _type string, mgetRequest MGetRequestContainer, args map[string]interface{}) (MGetResponseContainer, error) { var url string var retval MGetResponseContainer if len(index) <= 0 { url = fmt.Sprintf("/_mget") } if len(_type) > 0 && len(index) > 0 { url = fmt.Sprintf("/%s/%s/_mget", index, _type) } else if len(index) > 0 { url = fmt.Sprintf("/%s/_mget", index) } body, err := c.DoCommand("GET", url, args, mgetRequest) if err != nil { return retval, err } if err == nil { // marshall into json jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { return retval, jsonErr } } return retval, err } type MGetRequestContainer struct { Docs []MGetRequest `json:"docs"` } type MGetRequest struct { Index string `json:"_index"` Type string `json:"_type"` ID string `json:"_id"` IDS []string `json:"_ids,omitempty"` Fields []string `json:"fields,omitempty"` Routing string `json:"_routing,omitempty"` } type MGetResponseContainer struct { Docs []BaseResponse `json:"docs"` }
apache-2.0
ifintech/phplib
Ext/Aliyun/OTS/ProtoBuffer/pb_proto_ots.php
41144
<?php class PBError extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "PBString"; $this->values["2"] = ""; } function code() { return $this->_get_value("1"); } function set_code($value) { return $this->_set_value("1", $value); } function message() { return $this->_get_value("2"); } function set_message($value) { return $this->_set_value("2", $value); } } class ColumnType extends PBEnum { const INF_MIN = 0; const INF_MAX = 1; const INTEGER = 2; const STRING = 3; const BOOLEAN = 4; const DOUBLE = 5; const BINARY = 6; } class ColumnSchema extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "ColumnType"; $this->values["2"] = ""; } function name() { return $this->_get_value("1"); } function set_name($value) { return $this->_set_value("1", $value); } function type() { return $this->_get_value("2"); } function set_type($value) { return $this->_set_value("2", $value); } } class ColumnValue extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "ColumnType"; $this->values["1"] = ""; $this->fields["2"] = "PBInt"; $this->values["2"] = ""; $this->fields["3"] = "PBString"; $this->values["3"] = ""; $this->fields["4"] = "PBBool"; $this->values["4"] = ""; $this->fields["5"] = "PBDouble"; $this->values["5"] = ""; $this->fields["6"] = "PBString"; $this->values["6"] = ""; } function type() { return $this->_get_value("1"); } function set_type($value) { return $this->_set_value("1", $value); } function v_int() { return $this->_get_value("2"); } function set_v_int($value) { return $this->_set_value("2", $value); } function v_string() { return $this->_get_value("3"); } function set_v_string($value) { return $this->_set_value("3", $value); } function v_bool() { return $this->_get_value("4"); } function set_v_bool($value) { return $this->_set_value("4", $value); } function v_double() { return $this->_get_value("5"); } function set_v_double($value) { return $this->_set_value("5", $value); } function v_binary() { return $this->_get_value("6"); } function set_v_binary($value) { return $this->_set_value("6", $value); } } class Column extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "ColumnValue"; $this->values["2"] = ""; } function name() { return $this->_get_value("1"); } function set_name($value) { return $this->_set_value("1", $value); } function value() { return $this->_get_value("2"); } function set_value($value) { return $this->_set_value("2", $value); } } class Row extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "Column"; $this->values["1"] = array(); $this->fields["2"] = "Column"; $this->values["2"] = array(); } function primary_key_columns($offset) { return $this->_get_arr_value("1", $offset); } function add_primary_key_columns() { return $this->_add_arr_value("1"); } function set_primary_key_columns($index, $value) { $this->_set_arr_value("1", $index, $value); } function remove_last_primary_key_columns() { $this->_remove_last_arr_value("1"); } function primary_key_columns_size() { return $this->_get_arr_size("1"); } function attribute_columns($offset) { return $this->_get_arr_value("2", $offset); } function add_attribute_columns() { return $this->_add_arr_value("2"); } function set_attribute_columns($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_attribute_columns() { $this->_remove_last_arr_value("2"); } function attribute_columns_size() { return $this->_get_arr_size("2"); } } class TableMeta extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "ColumnSchema"; $this->values["2"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function primary_key($offset) { return $this->_get_arr_value("2", $offset); } function add_primary_key() { return $this->_add_arr_value("2"); } function set_primary_key($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("2"); } function primary_key_size() { return $this->_get_arr_size("2"); } } class RowExistenceExpectation extends PBEnum { const IGNORE = 0; const EXPECT_EXIST = 1; const EXPECT_NOT_EXIST = 2; } class Condition extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "RowExistenceExpectation"; $this->values["1"] = ""; } function row_existence() { return $this->_get_value("1"); } function set_row_existence($value) { return $this->_set_value("1", $value); } } class CapacityUnit extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBInt"; $this->values["1"] = ""; $this->fields["2"] = "PBInt"; $this->values["2"] = ""; } function read() { return $this->_get_value("1"); } function set_read($value) { return $this->_set_value("1", $value); } function write() { return $this->_get_value("2"); } function set_write($value) { return $this->_set_value("2", $value); } } class ReservedThroughputDetails extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "CapacityUnit"; $this->values["1"] = ""; $this->fields["2"] = "PBInt"; $this->values["2"] = ""; $this->fields["3"] = "PBInt"; $this->values["3"] = ""; $this->fields["4"] = "PBInt"; $this->values["4"] = ""; } function capacity_unit() { return $this->_get_value("1"); } function set_capacity_unit($value) { return $this->_set_value("1", $value); } function last_increase_time() { return $this->_get_value("2"); } function set_last_increase_time($value) { return $this->_set_value("2", $value); } function last_decrease_time() { return $this->_get_value("3"); } function set_last_decrease_time($value) { return $this->_set_value("3", $value); } function number_of_decreases_today() { return $this->_get_value("4"); } function set_number_of_decreases_today($value) { return $this->_set_value("4", $value); } } class ReservedThroughput extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "CapacityUnit"; $this->values["1"] = ""; } function capacity_unit() { return $this->_get_value("1"); } function set_capacity_unit($value) { return $this->_set_value("1", $value); } } class ConsumedCapacity extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "CapacityUnit"; $this->values["1"] = ""; } function capacity_unit() { return $this->_get_value("1"); } function set_capacity_unit($value) { return $this->_set_value("1", $value); } } class CreateTableRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "TableMeta"; $this->values["1"] = ""; $this->fields["2"] = "ReservedThroughput"; $this->values["2"] = ""; } function table_meta() { return $this->_get_value("1"); } function set_table_meta($value) { return $this->_set_value("1", $value); } function reserved_throughput() { return $this->_get_value("2"); } function set_reserved_throughput($value) { return $this->_set_value("2", $value); } } class UpdateTableRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "ReservedThroughput"; $this->values["2"] = ""; } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function reserved_throughput() { return $this->_get_value("2"); } function set_reserved_throughput($value) { return $this->_set_value("2", $value); } } class UpdateTableResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "ReservedThroughputDetails"; $this->values["1"] = ""; } function reserved_throughput_details() { return $this->_get_value("1"); } function set_reserved_throughput_details($value) { return $this->_set_value("1", $value); } } class DescribeTableRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } } class DescribeTableResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "TableMeta"; $this->values["1"] = ""; $this->fields["2"] = "ReservedThroughputDetails"; $this->values["2"] = ""; } function table_meta() { return $this->_get_value("1"); } function set_table_meta($value) { return $this->_set_value("1", $value); } function reserved_throughput_details() { return $this->_get_value("2"); } function set_reserved_throughput_details($value) { return $this->_set_value("2", $value); } } class ListTableRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; } function ncvonline() { return $this->_get_value("1"); } function set_ncvonline($value) { return $this->_set_value("1", $value); } } class ListTableResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = array(); } function table_names($offset) { $v = $this->_get_arr_value("1", $offset); return $v->get_value(); } function append_table_names($value) { $v = $this->_add_arr_value("1"); $v->set_value($value); } function set_table_names($index, $value) { $v = new $this->fields["1"](); $v->set_value($value); $this->_set_arr_value("1", $index, $v); } function remove_last_table_names() { $this->_remove_last_arr_value("1"); } function table_names_size() { return $this->_get_arr_size("1"); } } class DeleteTableRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } } class GetRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "Column"; $this->values["2"] = array(); $this->fields["3"] = "PBString"; $this->values["3"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function primary_key($offset) { return $this->_get_arr_value("2", $offset); } function add_primary_key() { return $this->_add_arr_value("2"); } function set_primary_key($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("2"); } function primary_key_size() { return $this->_get_arr_size("2"); } function columns_to_get($offset) { $v = $this->_get_arr_value("3", $offset); return $v->get_value(); } function append_columns_to_get($value) { $v = $this->_add_arr_value("3"); $v->set_value($value); } function set_columns_to_get($index, $value) { $v = new $this->fields["3"](); $v->set_value($value); $this->_set_arr_value("3", $index, $v); } function remove_last_columns_to_get() { $this->_remove_last_arr_value("3"); } function columns_to_get_size() { return $this->_get_arr_size("3"); } } class GetRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "ConsumedCapacity"; $this->values["1"] = ""; $this->fields["2"] = "Row"; $this->values["2"] = ""; } function consumed() { return $this->_get_value("1"); } function set_consumed($value) { return $this->_set_value("1", $value); } function row() { return $this->_get_value("2"); } function set_row($value) { return $this->_set_value("2", $value); } } class OperationType extends PBEnum { const PUT = 1; const DELETE = 2; } class ColumnUpdate extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "OperationType"; $this->values["1"] = ""; $this->fields["2"] = "PBString"; $this->values["2"] = ""; $this->fields["3"] = "ColumnValue"; $this->values["3"] = ""; } function type() { return $this->_get_value("1"); } function set_type($value) { return $this->_set_value("1", $value); } function name() { return $this->_get_value("2"); } function set_name($value) { return $this->_set_value("2", $value); } function value() { return $this->_get_value("3"); } function set_value($value) { return $this->_set_value("3", $value); } } class UpdateRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "Condition"; $this->values["2"] = ""; $this->fields["3"] = "Column"; $this->values["3"] = array(); $this->fields["4"] = "ColumnUpdate"; $this->values["4"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function condition() { return $this->_get_value("2"); } function set_condition($value) { return $this->_set_value("2", $value); } function primary_key($offset) { return $this->_get_arr_value("3", $offset); } function add_primary_key() { return $this->_add_arr_value("3"); } function set_primary_key($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("3"); } function primary_key_size() { return $this->_get_arr_size("3"); } function attribute_columns($offset) { return $this->_get_arr_value("4", $offset); } function add_attribute_columns() { return $this->_add_arr_value("4"); } function set_attribute_columns($index, $value) { $this->_set_arr_value("4", $index, $value); } function remove_last_attribute_columns() { $this->_remove_last_arr_value("4"); } function attribute_columns_size() { return $this->_get_arr_size("4"); } } class UpdateRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "ConsumedCapacity"; $this->values["1"] = ""; } function consumed() { return $this->_get_value("1"); } function set_consumed($value) { return $this->_set_value("1", $value); } } class PutRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "Condition"; $this->values["2"] = ""; $this->fields["3"] = "Column"; $this->values["3"] = array(); $this->fields["4"] = "Column"; $this->values["4"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function condition() { return $this->_get_value("2"); } function set_condition($value) { return $this->_set_value("2", $value); } function primary_key($offset) { return $this->_get_arr_value("3", $offset); } function add_primary_key() { return $this->_add_arr_value("3"); } function set_primary_key($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("3"); } function primary_key_size() { return $this->_get_arr_size("3"); } function attribute_columns($offset) { return $this->_get_arr_value("4", $offset); } function add_attribute_columns() { return $this->_add_arr_value("4"); } function set_attribute_columns($index, $value) { $this->_set_arr_value("4", $index, $value); } function remove_last_attribute_columns() { $this->_remove_last_arr_value("4"); } function attribute_columns_size() { return $this->_get_arr_size("4"); } } class PutRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "ConsumedCapacity"; $this->values["1"] = ""; } function consumed() { return $this->_get_value("1"); } function set_consumed($value) { return $this->_set_value("1", $value); } } class DeleteRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "Condition"; $this->values["2"] = ""; $this->fields["3"] = "Column"; $this->values["3"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function condition() { return $this->_get_value("2"); } function set_condition($value) { return $this->_set_value("2", $value); } function primary_key($offset) { return $this->_get_arr_value("3", $offset); } function add_primary_key() { return $this->_add_arr_value("3"); } function set_primary_key($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("3"); } function primary_key_size() { return $this->_get_arr_size("3"); } } class DeleteRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "ConsumedCapacity"; $this->values["1"] = ""; } function consumed() { return $this->_get_value("1"); } function set_consumed($value) { return $this->_set_value("1", $value); } } class RowInBatchGetRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "Column"; $this->values["1"] = array(); } function primary_key($offset) { return $this->_get_arr_value("1", $offset); } function add_primary_key() { return $this->_add_arr_value("1"); } function set_primary_key($index, $value) { $this->_set_arr_value("1", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("1"); } function primary_key_size() { return $this->_get_arr_size("1"); } } class TableInBatchGetRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "RowInBatchGetRowRequest"; $this->values["2"] = array(); $this->fields["3"] = "PBString"; $this->values["3"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function rows($offset) { return $this->_get_arr_value("2", $offset); } function add_rows() { return $this->_add_arr_value("2"); } function set_rows($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_rows() { $this->_remove_last_arr_value("2"); } function rows_size() { return $this->_get_arr_size("2"); } function columns_to_get($offset) { $v = $this->_get_arr_value("3", $offset); return $v->get_value(); } function append_columns_to_get($value) { $v = $this->_add_arr_value("3"); $v->set_value($value); } function set_columns_to_get($index, $value) { $v = new $this->fields["3"](); $v->set_value($value); $this->_set_arr_value("3", $index, $v); } function remove_last_columns_to_get() { $this->_remove_last_arr_value("3"); } function columns_to_get_size() { return $this->_get_arr_size("3"); } } class BatchGetRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "TableInBatchGetRowRequest"; $this->values["1"] = array(); } function tables($offset) { return $this->_get_arr_value("1", $offset); } function add_tables() { return $this->_add_arr_value("1"); } function set_tables($index, $value) { $this->_set_arr_value("1", $index, $value); } function remove_last_tables() { $this->_remove_last_arr_value("1"); } function tables_size() { return $this->_get_arr_size("1"); } } class RowInBatchGetRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBBool"; $this->values["1"] = ""; $this->fields["2"] = "Error"; $this->values["2"] = ""; $this->fields["3"] = "ConsumedCapacity"; $this->values["3"] = ""; $this->fields["4"] = "Row"; $this->values["4"] = ""; } function is_ok() { return $this->_get_value("1"); } function set_is_ok($value) { return $this->_set_value("1", $value); } function error() { return $this->_get_value("2"); } function set_error($value) { return $this->_set_value("2", $value); } function consumed() { return $this->_get_value("3"); } function set_consumed($value) { return $this->_set_value("3", $value); } function row() { return $this->_get_value("4"); } function set_row($value) { return $this->_set_value("4", $value); } } class TableInBatchGetRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "RowInBatchGetRowResponse"; $this->values["2"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function rows($offset) { return $this->_get_arr_value("2", $offset); } function add_rows() { return $this->_add_arr_value("2"); } function set_rows($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_rows() { $this->_remove_last_arr_value("2"); } function rows_size() { return $this->_get_arr_size("2"); } } class BatchGetRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "TableInBatchGetRowResponse"; $this->values["1"] = array(); } function tables($offset) { return $this->_get_arr_value("1", $offset); } function add_tables() { return $this->_add_arr_value("1"); } function set_tables($index, $value) { $this->_set_arr_value("1", $index, $value); } function remove_last_tables() { $this->_remove_last_arr_value("1"); } function tables_size() { return $this->_get_arr_size("1"); } } class PutRowInBatchWriteRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "Condition"; $this->values["1"] = ""; $this->fields["2"] = "Column"; $this->values["2"] = array(); $this->fields["3"] = "Column"; $this->values["3"] = array(); } function condition() { return $this->_get_value("1"); } function set_condition($value) { return $this->_set_value("1", $value); } function primary_key($offset) { return $this->_get_arr_value("2", $offset); } function add_primary_key() { return $this->_add_arr_value("2"); } function set_primary_key($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("2"); } function primary_key_size() { return $this->_get_arr_size("2"); } function attribute_columns($offset) { return $this->_get_arr_value("3", $offset); } function add_attribute_columns() { return $this->_add_arr_value("3"); } function set_attribute_columns($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_attribute_columns() { $this->_remove_last_arr_value("3"); } function attribute_columns_size() { return $this->_get_arr_size("3"); } } class UpdateRowInBatchWriteRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "Condition"; $this->values["1"] = ""; $this->fields["2"] = "Column"; $this->values["2"] = array(); $this->fields["3"] = "ColumnUpdate"; $this->values["3"] = array(); } function condition() { return $this->_get_value("1"); } function set_condition($value) { return $this->_set_value("1", $value); } function primary_key($offset) { return $this->_get_arr_value("2", $offset); } function add_primary_key() { return $this->_add_arr_value("2"); } function set_primary_key($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("2"); } function primary_key_size() { return $this->_get_arr_size("2"); } function attribute_columns($offset) { return $this->_get_arr_value("3", $offset); } function add_attribute_columns() { return $this->_add_arr_value("3"); } function set_attribute_columns($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_attribute_columns() { $this->_remove_last_arr_value("3"); } function attribute_columns_size() { return $this->_get_arr_size("3"); } } class DeleteRowInBatchWriteRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "Condition"; $this->values["1"] = ""; $this->fields["2"] = "Column"; $this->values["2"] = array(); } function condition() { return $this->_get_value("1"); } function set_condition($value) { return $this->_set_value("1", $value); } function primary_key($offset) { return $this->_get_arr_value("2", $offset); } function add_primary_key() { return $this->_add_arr_value("2"); } function set_primary_key($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_primary_key() { $this->_remove_last_arr_value("2"); } function primary_key_size() { return $this->_get_arr_size("2"); } } class TableInBatchWriteRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "PutRowInBatchWriteRowRequest"; $this->values["2"] = array(); $this->fields["3"] = "UpdateRowInBatchWriteRowRequest"; $this->values["3"] = array(); $this->fields["4"] = "DeleteRowInBatchWriteRowRequest"; $this->values["4"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function put_rows($offset) { return $this->_get_arr_value("2", $offset); } function add_put_rows() { return $this->_add_arr_value("2"); } function set_put_rows($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_put_rows() { $this->_remove_last_arr_value("2"); } function put_rows_size() { return $this->_get_arr_size("2"); } function update_rows($offset) { return $this->_get_arr_value("3", $offset); } function add_update_rows() { return $this->_add_arr_value("3"); } function set_update_rows($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_update_rows() { $this->_remove_last_arr_value("3"); } function update_rows_size() { return $this->_get_arr_size("3"); } function delete_rows($offset) { return $this->_get_arr_value("4", $offset); } function add_delete_rows() { return $this->_add_arr_value("4"); } function set_delete_rows($index, $value) { $this->_set_arr_value("4", $index, $value); } function remove_last_delete_rows() { $this->_remove_last_arr_value("4"); } function delete_rows_size() { return $this->_get_arr_size("4"); } } class BatchWriteRowRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "TableInBatchWriteRowRequest"; $this->values["1"] = array(); } function tables($offset) { return $this->_get_arr_value("1", $offset); } function add_tables() { return $this->_add_arr_value("1"); } function set_tables($index, $value) { $this->_set_arr_value("1", $index, $value); } function remove_last_tables() { $this->_remove_last_arr_value("1"); } function tables_size() { return $this->_get_arr_size("1"); } } class RowInBatchWriteRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBBool"; $this->values["1"] = ""; $this->fields["2"] = "Error"; $this->values["2"] = ""; $this->fields["3"] = "ConsumedCapacity"; $this->values["3"] = ""; } function is_ok() { return $this->_get_value("1"); } function set_is_ok($value) { return $this->_set_value("1", $value); } function error() { return $this->_get_value("2"); } function set_error($value) { return $this->_set_value("2", $value); } function consumed() { return $this->_get_value("3"); } function set_consumed($value) { return $this->_set_value("3", $value); } } class TableInBatchWriteRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "RowInBatchWriteRowResponse"; $this->values["2"] = array(); $this->fields["3"] = "RowInBatchWriteRowResponse"; $this->values["3"] = array(); $this->fields["4"] = "RowInBatchWriteRowResponse"; $this->values["4"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function put_rows($offset) { return $this->_get_arr_value("2", $offset); } function add_put_rows() { return $this->_add_arr_value("2"); } function set_put_rows($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_put_rows() { $this->_remove_last_arr_value("2"); } function put_rows_size() { return $this->_get_arr_size("2"); } function update_rows($offset) { return $this->_get_arr_value("3", $offset); } function add_update_rows() { return $this->_add_arr_value("3"); } function set_update_rows($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_update_rows() { $this->_remove_last_arr_value("3"); } function update_rows_size() { return $this->_get_arr_size("3"); } function delete_rows($offset) { return $this->_get_arr_value("4", $offset); } function add_delete_rows() { return $this->_add_arr_value("4"); } function set_delete_rows($index, $value) { $this->_set_arr_value("4", $index, $value); } function remove_last_delete_rows() { $this->_remove_last_arr_value("4"); } function delete_rows_size() { return $this->_get_arr_size("4"); } } class BatchWriteRowResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "TableInBatchWriteRowResponse"; $this->values["1"] = array(); } function tables($offset) { return $this->_get_arr_value("1", $offset); } function add_tables() { return $this->_add_arr_value("1"); } function set_tables($index, $value) { $this->_set_arr_value("1", $index, $value); } function remove_last_tables() { $this->_remove_last_arr_value("1"); } function tables_size() { return $this->_get_arr_size("1"); } } class Direction extends PBEnum { const FORWARD = 0; const BACKWARD = 1; } class GetRangeRequest extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "PBString"; $this->values["1"] = ""; $this->fields["2"] = "Direction"; $this->values["2"] = ""; $this->fields["3"] = "PBString"; $this->values["3"] = array(); $this->fields["4"] = "PBInt"; $this->values["4"] = ""; $this->fields["5"] = "Column"; $this->values["5"] = array(); $this->fields["6"] = "Column"; $this->values["6"] = array(); } function table_name() { return $this->_get_value("1"); } function set_table_name($value) { return $this->_set_value("1", $value); } function direction() { return $this->_get_value("2"); } function set_direction($value) { return $this->_set_value("2", $value); } function columns_to_get($offset) { $v = $this->_get_arr_value("3", $offset); return $v->get_value(); } function append_columns_to_get($value) { $v = $this->_add_arr_value("3"); $v->set_value($value); } function set_columns_to_get($index, $value) { $v = new $this->fields["3"](); $v->set_value($value); $this->_set_arr_value("3", $index, $v); } function remove_last_columns_to_get() { $this->_remove_last_arr_value("3"); } function columns_to_get_size() { return $this->_get_arr_size("3"); } function limit() { return $this->_get_value("4"); } function set_limit($value) { return $this->_set_value("4", $value); } function inclusive_start_primary_key($offset) { return $this->_get_arr_value("5", $offset); } function add_inclusive_start_primary_key() { return $this->_add_arr_value("5"); } function set_inclusive_start_primary_key($index, $value) { $this->_set_arr_value("5", $index, $value); } function remove_last_inclusive_start_primary_key() { $this->_remove_last_arr_value("5"); } function inclusive_start_primary_key_size() { return $this->_get_arr_size("5"); } function exclusive_end_primary_key($offset) { return $this->_get_arr_value("6", $offset); } function add_exclusive_end_primary_key() { return $this->_add_arr_value("6"); } function set_exclusive_end_primary_key($index, $value) { $this->_set_arr_value("6", $index, $value); } function remove_last_exclusive_end_primary_key() { $this->_remove_last_arr_value("6"); } function exclusive_end_primary_key_size() { return $this->_get_arr_size("6"); } } class GetRangeResponse extends PBMessage { var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED; public function __construct($reader=null) { parent::__construct($reader); $this->fields["1"] = "ConsumedCapacity"; $this->values["1"] = ""; $this->fields["2"] = "Column"; $this->values["2"] = array(); $this->fields["3"] = "Row"; $this->values["3"] = array(); } function consumed() { return $this->_get_value("1"); } function set_consumed($value) { return $this->_set_value("1", $value); } function next_start_primary_key($offset) { return $this->_get_arr_value("2", $offset); } function add_next_start_primary_key() { return $this->_add_arr_value("2"); } function set_next_start_primary_key($index, $value) { $this->_set_arr_value("2", $index, $value); } function remove_last_next_start_primary_key() { $this->_remove_last_arr_value("2"); } function next_start_primary_key_size() { return $this->_get_arr_size("2"); } function rows($offset) { return $this->_get_arr_value("3", $offset); } function add_rows() { return $this->_add_arr_value("3"); } function set_rows($index, $value) { $this->_set_arr_value("3", $index, $value); } function remove_last_rows() { $this->_remove_last_arr_value("3"); } function rows_size() { return $this->_get_arr_size("3"); } } ?>
apache-2.0
SAP/openui5
src/sap.uxap/test/sap/uxap/demokit/sample/ObjectPageHeaderBackgroundDesign/Component.js
222
sap.ui.define(["sap/ui/core/UIComponent"], function (UIComponent) { "use strict"; return UIComponent.extend("sap.uxap.sample.ObjectPageHeaderBackgroundDesign.Component", { metadata: { manifest: "json" } }); });
apache-2.0
wemote/scorpio
scorpio-core/src/test/java/com/wemote/scorpio/modules/persistence/HibernatesTest.java
1752
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package com.wemote.scorpio.modules.persistence; import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.MySQL5InnoDBDialect; import org.hibernate.dialect.Oracle10gDialect; import org.junit.Test; import javax.sql.DataSource; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class HibernatesTest { @Test public void testGetDialect() throws SQLException { DataSource mockDataSource = mock(DataSource.class); Connection mockConnection = mock(Connection.class); DatabaseMetaData mockMetaData = mock(DatabaseMetaData.class); when(mockDataSource.getConnection()).thenReturn(mockConnection); when(mockConnection.getMetaData()).thenReturn(mockMetaData); when(mockMetaData.getURL()).thenReturn("jdbc:h2:file:~/test;AUTO_SERVER=TRUE"); String dialect = Hibernates.getDialect(mockDataSource); assertThat(dialect).isEqualTo(H2Dialect.class.getName()); when(mockMetaData.getURL()).thenReturn("jdbc:mysql://localhost:3306/test"); dialect = Hibernates.getDialect(mockDataSource); assertThat(dialect).isEqualTo(MySQL5InnoDBDialect.class.getName()); when(mockMetaData.getURL()).thenReturn("jdbc:oracle:thin:@127.0.0.1:1521:XE"); dialect = Hibernates.getDialect(mockDataSource); assertThat(dialect).isEqualTo(Oracle10gDialect.class.getName()); } }
apache-2.0
migangel9/storybp
Resources/android/alloy/controllers/tabComida.js
25744
function Controller() { function showMenu() { $.main.width = Ti.Platform.displayCaps.platformWidth; $.main.animate({ left: 300, duration: 100 }); } function hideMenu(e) { if (e.direction = "left") { $.main.width = Ti.UI.SIZE; $.main.animate({ left: 0, duration: 100 }); } } function showNews() { var win = Alloy.createController("noticia").getView(); win.open(); } function showAgenda() { var win = Alloy.createController("agenda").getView(); win.open(); } function showVida() { var win = Alloy.createController("vida").getView(); win.open(); } function showNews() { var win = Alloy.createController("index").getView(); win.open(); } function showComida() { var win = Alloy.createController("tabComidaSe").getView(); win.open(); } function showGrafica() { var win = Alloy.createController("tabGraficas").getView(); win.open(); } function showMonigote() { var win = Alloy.createController("vidaDieta").getView(); win.open(); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "tabComida"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; var __defers = {}; $.__views.tabComida = Ti.UI.createWindow({ backgroundColor: "white", orientationModes: [ Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT, Ti.UI.UPSIDE_PORTRAIT ], fullscreen: false, navBarHidden: true, id: "tabComida" }); $.__views.tabComida && $.addTopLevelView($.__views.tabComida); $.__views.menu = Ti.UI.createView({ height: Ti.UI.FILL, width: Ti.UI.FILL, backgroundColor: "#585B63", left: 0, id: "menu" }); $.__views.tabComida.add($.__views.menu); hideMenu ? $.__views.menu.addEventListener("swipe", hideMenu) : __defers["$.__views.menu!swipe!hideMenu"] = true; $.__views.options = Ti.UI.createView({ top: 0, left: 0, height: Ti.UI.SIZE, layout: "vertical", bubbleParent: false, backgroundColor: "#585B63", id: "options" }); $.__views.menu.add($.__views.options); $.__views.__alloyId339 = Ti.UI.createView({ top: "5", left: "5", height: 44, width: 290, borderColor: "#32384F", borderRadius: 5, borderWidht: 1, right: "5", bottom: "5", color: "#fff", backgroundColor: "#8A8C90", id: "__alloyId339" }); $.__views.options.add($.__views.__alloyId339); $.__views.__alloyId340 = Ti.UI.createLabel({ text: "Perfil", id: "__alloyId340" }); $.__views.__alloyId339.add($.__views.__alloyId340); $.__views.__alloyId341 = Ti.UI.createView({ top: "5", left: "5", height: 44, width: 290, borderColor: "#32384F", borderRadius: 5, borderWidht: 1, right: "5", bottom: "5", color: "#fff", backgroundColor: "#8A8C90", id: "__alloyId341" }); $.__views.options.add($.__views.__alloyId341); showAgenda ? $.__views.__alloyId341.addEventListener("click", showAgenda) : __defers["$.__views.__alloyId341!click!showAgenda"] = true; $.__views.__alloyId342 = Ti.UI.createLabel({ text: "Agenda", id: "__alloyId342" }); $.__views.__alloyId341.add($.__views.__alloyId342); $.__views.__alloyId343 = Ti.UI.createView({ top: "5", left: "5", height: 44, width: 290, borderColor: "#32384F", borderRadius: 5, borderWidht: 1, right: "5", bottom: "5", color: "#fff", backgroundColor: "#8A8C90", id: "__alloyId343" }); $.__views.options.add($.__views.__alloyId343); $.__views.__alloyId344 = Ti.UI.createLabel({ text: "Mensajes", id: "__alloyId344" }); $.__views.__alloyId343.add($.__views.__alloyId344); $.__views.__alloyId345 = Ti.UI.createView({ top: "5", left: "5", height: 44, width: 290, borderColor: "#32384F", borderRadius: 5, borderWidht: 1, right: "5", bottom: "5", color: "#fff", backgroundColor: "#8A8C90", id: "__alloyId345" }); $.__views.options.add($.__views.__alloyId345); showNews ? $.__views.__alloyId345.addEventListener("click", showNews) : __defers["$.__views.__alloyId345!click!showNews"] = true; $.__views.__alloyId346 = Ti.UI.createLabel({ text: "Noticias", id: "__alloyId346" }); $.__views.__alloyId345.add($.__views.__alloyId346); $.__views.__alloyId347 = Ti.UI.createView({ top: "5", left: "5", height: 44, width: 290, borderColor: "#32384F", borderRadius: 5, borderWidht: 1, right: "5", bottom: "5", color: "#fff", backgroundColor: "#8A8C90", id: "__alloyId347" }); $.__views.options.add($.__views.__alloyId347); showVida ? $.__views.__alloyId347.addEventListener("click", showVida) : __defers["$.__views.__alloyId347!click!showVida"] = true; $.__views.__alloyId348 = Ti.UI.createLabel({ text: "Vida Sana", id: "__alloyId348" }); $.__views.__alloyId347.add($.__views.__alloyId348); $.__views.main = Ti.UI.createView({ height: Ti.UI.FILL, width: Ti.UI.FILL, backgroundColor: "#D2D2D2", left: 0, layout: "vertical", id: "main" }); $.__views.tabComida.add($.__views.main); $.__views.iconBar = Ti.UI.createView({ backgroundGradient: { type: "linear", startPoint: { x: "0%", y: "0%" }, endPoint: { x: "0%", y: "100%" }, colors: [ { color: "#FF761B", offset: 0 }, { color: "#E66713", offset: 1 } ] }, width: Ti.UI.FILL, height: "54", id: "iconBar" }); $.__views.main.add($.__views.iconBar); $.__views.topActions = Ti.UI.createView({ width: "200", height: "50", layout: "horizontal", id: "topActions" }); $.__views.iconBar.add($.__views.topActions); $.__views.contactsBtn = Ti.UI.createImageView({ width: "30", height: "30", left: 20, top: 10, image: "/images/contactBtn.png", id: "contactsBtn" }); $.__views.topActions.add($.__views.contactsBtn); $.__views.eventBtn = Ti.UI.createImageView({ width: "30", height: "30", left: 20, top: 10, image: "/images/ic_action_event.png", id: "eventBtn" }); $.__views.topActions.add($.__views.eventBtn); showAgenda ? $.__views.eventBtn.addEventListener("click", showAgenda) : __defers["$.__views.eventBtn!click!showAgenda"] = true; $.__views.messagesBtn = Ti.UI.createImageView({ width: "30", height: "30", left: 20, top: 10, image: "/images/messagesBtn.png", id: "messagesBtn" }); $.__views.topActions.add($.__views.messagesBtn); $.__views.notificationsBtn = Ti.UI.createImageView({ width: "30", height: "30", left: 20, top: 10, image: "/images/notificationsBtn.png", id: "notificationsBtn" }); $.__views.topActions.add($.__views.notificationsBtn); $.__views.menuBtn = Ti.UI.createImageView({ left: 5, width: "35", height: "34", image: "/images/menuBtn.png", id: "menuBtn" }); $.__views.iconBar.add($.__views.menuBtn); showMenu ? $.__views.menuBtn.addEventListener("click", showMenu) : __defers["$.__views.menuBtn!click!showMenu"] = true; $.__views.searchBtn = Ti.UI.createImageView({ right: 5, width: "35", height: "34", image: "/images/searchBtn.png", id: "searchBtn" }); $.__views.iconBar.add($.__views.searchBtn); $.__views.menuBar = Ti.UI.createView({ backgroundColor: "#f5f6f9", width: Ti.UI.FILL, height: "45", layout: "horizontal", id: "menuBar" }); $.__views.main.add($.__views.menuBar); $.__views.__alloyId349 = Ti.UI.createView({ width: "33%", heigth: "45", id: "__alloyId349" }); $.__views.menuBar.add($.__views.__alloyId349); showComida ? $.__views.__alloyId349.addEventListener("click", showComida) : __defers["$.__views.__alloyId349!click!showComida"] = true; $.__views.comidaBtn = Ti.UI.createImageView({ width: "25", height: "25", image: "/images/comidaBtn.png", id: "comidaBtn" }); $.__views.__alloyId349.add($.__views.comidaBtn); $.__views.tabActive = Ti.UI.createView({ bottom: 0, height: "3", width: Ti.UI.FILL, backgroundColor: "#d07436", layout: "horizontal", id: "tabActive" }); $.__views.__alloyId349.add($.__views.tabActive); $.__views.__alloyId350 = Ti.UI.createView({ width: "33%", heigth: "45", id: "__alloyId350" }); $.__views.menuBar.add($.__views.__alloyId350); showGrafica ? $.__views.__alloyId350.addEventListener("click", showGrafica) : __defers["$.__views.__alloyId350!click!showGrafica"] = true; $.__views.graficasBtn = Ti.UI.createImageView({ width: "25", height: "25", image: "/images/graficasBtn.png", id: "graficasBtn" }); $.__views.__alloyId350.add($.__views.graficasBtn); $.__views.__alloyId351 = Ti.UI.createView({ width: "33%", heigth: "45", id: "__alloyId351" }); $.__views.menuBar.add($.__views.__alloyId351); showMonigote ? $.__views.__alloyId351.addEventListener("click", showMonigote) : __defers["$.__views.__alloyId351!click!showMonigote"] = true; $.__views.monigoteBtn = Ti.UI.createImageView({ width: "25", height: "25", image: "/images/monigoteBtn.png", id: "monigoteBtn" }); $.__views.__alloyId351.add($.__views.monigoteBtn); $.__views.saludometro = Ti.UI.createScrollView({ width: Ti.UI.FILL, backgroundColor: "#fff", layout: "vertical", id: "saludometro", showVerticalScrollIndicator: "true", scrollType: "vertical" }); $.__views.main.add($.__views.saludometro); var __alloyId352 = []; $.__views.v1 = Ti.UI.createView({ layout: "horizontal", id: "v1" }); __alloyId352.push($.__views.v1); $.__views.__alloyId353 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId353" }); $.__views.v1.add($.__views.__alloyId353); $.__views.__alloyId354 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/meatBtn.png", id: "__alloyId354" }); $.__views.__alloyId353.add($.__views.__alloyId354); $.__views.__alloyId355 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId355" }); $.__views.v1.add($.__views.__alloyId355); $.__views.__alloyId356 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/eggBtn.png", id: "__alloyId356" }); $.__views.__alloyId355.add($.__views.__alloyId356); $.__views.__alloyId357 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId357" }); $.__views.v1.add($.__views.__alloyId357); $.__views.__alloyId358 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/bananaBtn.png", id: "__alloyId358" }); $.__views.__alloyId357.add($.__views.__alloyId358); $.__views.v2 = Ti.UI.createView({ layout: "horizontal", id: "v2" }); __alloyId352.push($.__views.v2); $.__views.__alloyId359 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId359" }); $.__views.v2.add($.__views.__alloyId359); $.__views.__alloyId360 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/appleBtn.png", id: "__alloyId360" }); $.__views.__alloyId359.add($.__views.__alloyId360); $.__views.__alloyId361 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId361" }); $.__views.v2.add($.__views.__alloyId361); $.__views.__alloyId362 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/friesBtn.png", id: "__alloyId362" }); $.__views.__alloyId361.add($.__views.__alloyId362); $.__views.__alloyId363 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId363" }); $.__views.v2.add($.__views.__alloyId363); $.__views.__alloyId364 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/burguerBtn.png", id: "__alloyId364" }); $.__views.__alloyId363.add($.__views.__alloyId364); $.__views.v3 = Ti.UI.createView({ layout: "horizontal", id: "v3" }); __alloyId352.push($.__views.v3); $.__views.__alloyId365 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId365" }); $.__views.v3.add($.__views.__alloyId365); $.__views.__alloyId366 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/pizzaBtn.png", id: "__alloyId366" }); $.__views.__alloyId365.add($.__views.__alloyId366); $.__views.__alloyId367 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId367" }); $.__views.v3.add($.__views.__alloyId367); $.__views.__alloyId368 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/tomatoBtn.png", id: "__alloyId368" }); $.__views.__alloyId367.add($.__views.__alloyId368); $.__views.__alloyId369 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId369" }); $.__views.v3.add($.__views.__alloyId369); $.__views.__alloyId370 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/chickenBtn.png", id: "__alloyId370" }); $.__views.__alloyId369.add($.__views.__alloyId370); $.__views.scrollView = Ti.UI.createScrollableView({ width: Ti.UI.FILL, height: 65, backgroundColor: "#E3E3E3", views: __alloyId352, id: "scrollView", showPagingControl: "true" }); $.__views.saludometro.add($.__views.scrollView); var __alloyId371 = []; $.__views.v1 = Ti.UI.createView({ layout: "horizontal", id: "v1" }); __alloyId371.push($.__views.v1); $.__views.__alloyId372 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId372" }); $.__views.v1.add($.__views.__alloyId372); $.__views.__alloyId373 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/appleBtn.png", id: "__alloyId373" }); $.__views.__alloyId372.add($.__views.__alloyId373); $.__views.__alloyId374 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId374" }); $.__views.v1.add($.__views.__alloyId374); $.__views.__alloyId375 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/friesBtn.png", id: "__alloyId375" }); $.__views.__alloyId374.add($.__views.__alloyId375); $.__views.__alloyId376 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId376" }); $.__views.v1.add($.__views.__alloyId376); $.__views.__alloyId377 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/burguerBtn.png", id: "__alloyId377" }); $.__views.__alloyId376.add($.__views.__alloyId377); $.__views.v2 = Ti.UI.createView({ layout: "horizontal", id: "v2" }); __alloyId371.push($.__views.v2); $.__views.__alloyId378 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId378" }); $.__views.v2.add($.__views.__alloyId378); $.__views.__alloyId379 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/meatBtn.png", id: "__alloyId379" }); $.__views.__alloyId378.add($.__views.__alloyId379); $.__views.__alloyId380 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId380" }); $.__views.v2.add($.__views.__alloyId380); $.__views.__alloyId381 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/eggBtn.png", id: "__alloyId381" }); $.__views.__alloyId380.add($.__views.__alloyId381); $.__views.__alloyId382 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId382" }); $.__views.v2.add($.__views.__alloyId382); $.__views.__alloyId383 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/bananaBtn.png", id: "__alloyId383" }); $.__views.__alloyId382.add($.__views.__alloyId383); $.__views.v3 = Ti.UI.createView({ layout: "horizontal", id: "v3" }); __alloyId371.push($.__views.v3); $.__views.__alloyId384 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId384" }); $.__views.v3.add($.__views.__alloyId384); $.__views.__alloyId385 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/pizzaBtn.png", id: "__alloyId385" }); $.__views.__alloyId384.add($.__views.__alloyId385); $.__views.__alloyId386 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId386" }); $.__views.v3.add($.__views.__alloyId386); $.__views.__alloyId387 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/tomatoBtn.png", id: "__alloyId387" }); $.__views.__alloyId386.add($.__views.__alloyId387); $.__views.__alloyId388 = Ti.UI.createView({ width: "33%", height: "55dp", id: "__alloyId388" }); $.__views.v3.add($.__views.__alloyId388); $.__views.__alloyId389 = Ti.UI.createImageView({ top: 10, width: "55dp", height: "55dp", image: "/images/chickenBtn.png", id: "__alloyId389" }); $.__views.__alloyId388.add($.__views.__alloyId389); $.__views.scrollView = Ti.UI.createScrollableView({ width: Ti.UI.FILL, height: 65, backgroundColor: "#E3E3E3", views: __alloyId371, id: "scrollView", showPagingControl: "true" }); $.__views.saludometro.add($.__views.scrollView); $.__views.platillo = Ti.UI.createView({ width: Ti.UI.FILL, height: 150, backgroundColor: "#fff", id: "platillo" }); $.__views.saludometro.add($.__views.platillo); $.__views.__alloyId390 = Ti.UI.createImageView({ image: "/images/plato.png", id: "__alloyId390" }); $.__views.platillo.add($.__views.__alloyId390); $.__views.__alloyId391 = Ti.UI.createImageView({ height: "35", width: "35", right: "15", image: "/images/scanBtn.png", id: "__alloyId391" }); $.__views.platillo.add($.__views.__alloyId391); $.__views.recomendaciones = Ti.UI.createView({ backgroundColor: "#1BC123", color: "#fff", borderRadius: 5, borderWidht: 1, left: "5", right: "5", top: "5", width: Ti.UI.FILL, height: "45", id: "recomendaciones" }); $.__views.saludometro.add($.__views.recomendaciones); $.__views.__alloyId392 = Ti.UI.createLabel({ text: "Te recomendamos que agregues jitomate a tu comida, esta te ayudara a subir el nivel de ...", color: "#fff", left: "5", right: "5", id: "__alloyId392" }); $.__views.recomendaciones.add($.__views.__alloyId392); $.__views.saludLbl = Ti.UI.createLabel({ top: 10, left: 10, color: "#000", text: "Saludometro", id: "saludLbl" }); $.__views.saludometro.add($.__views.saludLbl); $.__views.saludPuntajeLbl = Ti.UI.createLabel({ right: 10, color: "#000", text: "+ 14 pts", id: "saludPuntajeLbl" }); $.__views.saludometro.add($.__views.saludPuntajeLbl); $.__views.__alloyId393 = Ti.UI.createView({ height: "35dp", width: Ti.UI.SIZE, id: "__alloyId393" }); $.__views.saludometro.add($.__views.__alloyId393); $.__views.pb = Ti.UI.createProgressBar({ id: "pb", min: "0", width: "80%", max: "100", value: "30", color: "#000", message: "Granos" }); $.__views.__alloyId393.add($.__views.pb); $.__views.__alloyId394 = Ti.UI.createView({ height: "35dp", width: Ti.UI.SIZE, id: "__alloyId394" }); $.__views.saludometro.add($.__views.__alloyId394); $.__views.pb2 = Ti.UI.createProgressBar({ id: "pb2", min: "0", width: "80%", max: "100", value: "50", color: "#000", message: "Verduras" }); $.__views.__alloyId394.add($.__views.pb2); $.__views.__alloyId395 = Ti.UI.createView({ height: "35dp", width: Ti.UI.SIZE, id: "__alloyId395" }); $.__views.saludometro.add($.__views.__alloyId395); $.__views.pb3 = Ti.UI.createProgressBar({ id: "pb3", min: "0", width: "80%", max: "100", value: "85", message: "Frutas" }); $.__views.__alloyId395.add($.__views.pb3); $.__views.__alloyId396 = Ti.UI.createView({ height: "35dp", width: Ti.UI.SIZE, id: "__alloyId396" }); $.__views.saludometro.add($.__views.__alloyId396); $.__views.pb3 = Ti.UI.createProgressBar({ id: "pb3", min: "0", width: "80%", max: "100", value: "65", message: "Lacteos" }); $.__views.__alloyId396.add($.__views.pb3); $.__views.__alloyId397 = Ti.UI.createView({ height: "35dp", width: Ti.UI.SIZE, id: "__alloyId397" }); $.__views.saludometro.add($.__views.__alloyId397); $.__views.pb3 = Ti.UI.createProgressBar({ id: "pb3", min: "0", width: "80%", max: "100", value: "45", message: "Grasas" }); $.__views.__alloyId397.add($.__views.pb3); $.__views.__alloyId398 = Ti.UI.createView({ height: "35dp", width: Ti.UI.SIZE, id: "__alloyId398" }); $.__views.saludometro.add($.__views.__alloyId398); $.__views.pb3 = Ti.UI.createProgressBar({ id: "pb3", min: "0", width: "80%", max: "100", value: "15", message: "Carne" }); $.__views.__alloyId398.add($.__views.pb3); $.__views.button = Ti.UI.createButton({ id: "button", title: "Enviar", top: "10", width: "100", height: "50", bottom: "15" }); $.__views.saludometro.add($.__views.button); exports.destroy = function() {}; _.extend($, $.__views); __defers["$.__views.menu!swipe!hideMenu"] && $.__views.menu.addEventListener("swipe", hideMenu); __defers["$.__views.__alloyId341!click!showAgenda"] && $.__views.__alloyId341.addEventListener("click", showAgenda); __defers["$.__views.__alloyId345!click!showNews"] && $.__views.__alloyId345.addEventListener("click", showNews); __defers["$.__views.__alloyId347!click!showVida"] && $.__views.__alloyId347.addEventListener("click", showVida); __defers["$.__views.eventBtn!click!showAgenda"] && $.__views.eventBtn.addEventListener("click", showAgenda); __defers["$.__views.menuBtn!click!showMenu"] && $.__views.menuBtn.addEventListener("click", showMenu); __defers["$.__views.__alloyId349!click!showComida"] && $.__views.__alloyId349.addEventListener("click", showComida); __defers["$.__views.__alloyId350!click!showGrafica"] && $.__views.__alloyId350.addEventListener("click", showGrafica); __defers["$.__views.__alloyId351!click!showMonigote"] && $.__views.__alloyId351.addEventListener("click", showMonigote); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
apache-2.0
Assassinss/smile
src/main/java/me/zsj/smile/widget/PullBackLayout.java
4071
package me.zsj.smile.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.support.v4.view.ViewCompat; import android.support.v4.widget.ViewDragHelper; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import me.zsj.smile.utils.ScreenUtils; /** * Created by zsj on 2015/11/1 0001. */ public class PullBackLayout extends FrameLayout{ private ViewDragHelper mDragHelper; private int mReleasedHeight; private PullCallBack pullCallBack; private FrameLayout mBackgroudLayout; private ColorDrawable mBackgroud; public void setPullCallBack(PullCallBack pullCallBack) { this.pullCallBack = pullCallBack; } public PullBackLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PullBackLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mDragHelper = ViewDragHelper.create(this, 1f / 8f, new DragCallBack()); mReleasedHeight = ScreenUtils.getHeight(context) / 6; mBackgroud = new ColorDrawable(Color.BLACK); } class DragCallBack extends ViewDragHelper.Callback { @Override public boolean tryCaptureView(View child, int pointerId) { return true; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { return 0; } @Override public int getViewHorizontalDragRange(View child) { return 0; } @Override public int clampViewPositionVertical(View child, int top, int dy) { return Math.max(0, top); } @Override public int getViewVerticalDragRange(View child) { return getHeight(); } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { super.onViewReleased(releasedChild, xvel, yvel); if (releasedChild == null) return; if (releasedChild.getTop() >= mReleasedHeight) { if (pullCallBack != null) { pullCallBack.onPullCompleted(); } }else { mDragHelper.settleCapturedViewAt(0, 0); invalidate(); } } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { super.onViewPositionChanged(changedView, left, top, dx, dy); float progress = Math.min(1f, ((float)top / (float)getHeight()) * 5f); mBackgroud.setAlpha((int) (0xff * (1f - progress))); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mBackgroudLayout = (FrameLayout) getChildAt(0); if (mBackgroudLayout != null) mBackgroudLayout.setBackground(mBackgroud); } @Override public void computeScroll() { super.computeScroll(); if (mDragHelper.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { //这么做的目的是当图片缩小时应用会发生下标越界异常, // 接着捕捉异常返回false,子View可以继续处理事件分发,应用就不会crash了 try { return mDragHelper.shouldInterceptTouchEvent(ev); }catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean onTouchEvent(MotionEvent event) { mDragHelper.processTouchEvent(event); return true; } public interface PullCallBack { void onPullCompleted(); } }
apache-2.0
nickbabcock/dropwizard
dropwizard-forms/src/test/java/io/dropwizard/forms/MultiPartBundleTest.java
1035
package io.dropwizard.forms; import com.codahale.metrics.MetricRegistry; import io.dropwizard.Configuration; import io.dropwizard.jackson.Jackson; import io.dropwizard.logging.BootstrapLogging; import io.dropwizard.setup.Environment; import io.dropwizard.validation.BaseValidator; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MultiPartBundleTest { static { BootstrapLogging.bootstrap(); } @Test public void testRun() throws Exception { final Environment environment = new Environment( "multipart-test", Jackson.newObjectMapper(), BaseValidator.newValidator(), new MetricRegistry(), getClass().getClassLoader() ); new MultiPartBundle().run(new Configuration(), environment); assertThat(environment.jersey().getResourceConfig().getClasses()).contains(MultiPartFeature.class); } }
apache-2.0
Seriane/Pokedex
src/js/components/Main.js
296
import React from "react"; import Pokedex from "./Pokedex" import Soundtrack from "./Soundtrack" import Logo from "./Logo" export default class Main extends React.Component { render() { return ( <div id = "container" > <Logo /> <Pokedex /> <Soundtrack /> </div> ); } }
apache-2.0
RizkiMufrizal/Starter-Project
Starter-FrontEnd/src/environments/environment.ts
462
// The file contents for the current environment will overwrite these during build. // The build system defaults to the dev environment which uses `environment.ts`, but if you do // `ng build --env=prod` then `environment.prod.ts` will be used instead. // The list of which env maps to which file can be found in `.angular-cli.json`. export const environment = { production: false, clientId: 'clientid', clientSecret: 'secret', grantType: 'password' };
apache-2.0
chiaming0914/awe-cpp-sdk
aws-cpp-sdk-inspector/source/model/DescribeAssessmentResult.cpp
1430
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #include <aws/inspector/model/DescribeAssessmentResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Inspector::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeAssessmentResult::DescribeAssessmentResult() { } DescribeAssessmentResult::DescribeAssessmentResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribeAssessmentResult& DescribeAssessmentResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("assessment")) { m_assessment = jsonValue.GetObject("assessment"); } return *this; }
apache-2.0
DeinDesign/css
node_modules/grunt-contrib-watch/node_modules/tiny-lr/node_modules/qs/test/parse.js
4655
if (require.register) { var qs = require('querystring'); } else { var qs = require('../') , expect = require('expect.js'); } describe('qs.parse()', function () { it('should support the basics', function () { expect(qs.parse('0=foo')).to.eql({'0': 'foo'}); expect(qs.parse('foo=c++')) .to.eql({foo: 'c '}); expect(qs.parse('a[>=]=23')) .to.eql({a: {'>=': '23'}}); expect(qs.parse('a[<=>]==23')) .to.eql({a: {'<=>': '=23'}}); expect(qs.parse('a[==]=23')) .to.eql({a: {'==': '23'}}); expect(qs.parse('foo')) .to.eql({foo: ''}); expect(qs.parse('foo=bar')) .to.eql({foo: 'bar'}); expect(qs.parse(' foo = bar = baz ')) .to.eql({' foo ': ' bar = baz '}); expect(qs.parse('foo=bar=baz')) .to.eql({foo: 'bar=baz'}); expect(qs.parse('foo=bar&bar=baz')) .to.eql({foo: 'bar', bar: 'baz'}); expect(qs.parse('foo=bar&baz')) .to.eql({foo: 'bar', baz: ''}); expect(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')) .to.eql({ cht: 'p3' , chd: 't:60,40' , chs: '250x100' , chl: 'Hello|World' }); }) it('should support encoded = signs', function () { expect(qs.parse('he%3Dllo=th%3Dere')) .to.eql({'he=llo': 'th=ere'}); }) it('should support nesting', function () { expect(qs.parse('ops[>=]=25')) .to.eql({ops: {'>=': '25'}}); expect(qs.parse('user[name]=tj')) .to.eql({user: {name: 'tj'}}); expect(qs.parse('user[name][first]=tj&user[name][last]=holowaychuk')) .to.eql({user: {name: {first: 'tj', last: 'holowaychuk'}}}); }) it('should support array notation', function () { expect(qs.parse('images[]')) .to.eql({images: []}); expect(qs.parse('user[]=tj')) .to.eql({user: ['tj']}); expect(qs.parse('user[]=tj&user[]=tobi&user[]=jane')) .to.eql({user: ['tj', 'tobi', 'jane']}); expect(qs.parse('user[names][]=tj&user[names][]=tyler')) .to.eql({user: {names: ['tj', 'tyler']}}); expect(qs.parse('user[names][]=tj&user[names][]=tyler&user[email]=tj@vision-media.ca')) .to.eql({user: {names: ['tj', 'tyler'], email: 'tj@vision-media.ca'}}); expect(qs.parse('items=a&items=b')) .to.eql({items: ['a', 'b']}); expect(qs.parse('user[names]=tj&user[names]=holowaychuk&user[names]=TJ')) .to.eql({user: {names: ['tj', 'holowaychuk', 'TJ']}}); expect(qs.parse('user[name][first]=tj&user[name][first]=TJ')) .to.eql({user: {name: {first: ['tj', 'TJ']}}}); var o = qs.parse('existing[fcbaebfecc][name][last]=tj') expect(o).to.eql({existing: {'fcbaebfecc': {name: {last: 'tj'}}}}) expect(Array.isArray(o.existing)).to.equal(false); }) it('should support arrays with indexes', function () { expect(qs.parse('foo[0]=bar&foo[1]=baz')).to.eql({foo: ['bar', 'baz']}); expect(qs.parse('foo[1]=bar&foo[0]=baz')).to.eql({foo: ['baz', 'bar']}); expect(qs.parse('foo[base64]=RAWR')).to.eql({foo: {base64: 'RAWR'}}); expect(qs.parse('foo[64base]=RAWR')).to.eql({foo: {'64base': 'RAWR'}}); }) it('should expand to an array when dupliate keys are present', function () { expect(qs.parse('items=bar&items=baz&items=raz')) .to.eql({items: ['bar', 'baz', 'raz']}); }) it('should support right-hand side brackets', function () { expect(qs.parse('pets=["tobi"]')) .to.eql({pets: '["tobi"]'}); expect(qs.parse('operators=[">=", "<="]')) .to.eql({operators: '[">=", "<="]'}); expect(qs.parse('op[>=]=[1,2,3]')) .to.eql({op: {'>=': '[1,2,3]'}}); expect(qs.parse('op[>=]=[1,2,3]&op[=]=[[[[1]]]]')) .to.eql({op: {'>=': '[1,2,3]', '=': '[[[[1]]]]'}}); }) it('should support empty values', function () { expect(qs.parse('')).to.eql({}); expect(qs.parse(undefined)).to.eql({}); expect(qs.parse(null)).to.eql({}); }) it('should transform arrays to objects', function () { expect(qs.parse('foo[0]=bar&foo[bad]=baz')).to.eql({foo: {0: "bar", bad: "baz"}}); expect(qs.parse('foo[bad]=baz&foo[0]=bar')).to.eql({foo: {0: "bar", bad: "baz"}}); }) it('should support malformed uri chars', function () { expect(qs.parse('{%:%}')).to.eql({'{%:%}': ''}); expect(qs.parse('foo=%:%}')).to.eql({'foo': '%:%}'}); }) it('should support semi-parsed strings', function () { expect(qs.parse({'user[name]': 'tobi'})) .to.eql({user: {name: 'tobi'}}); expect(qs.parse({'user[name]': 'tobi', 'user[email][main]': 'tobi@lb.com'})) .to.eql({user: {name: 'tobi', email: {main: 'tobi@lb.com'}}}); }) it('should not produce empty keys', function () { expect(qs.parse('_r=1&')) .to.eql({_r: '1'}) }) })
apache-2.0
alain75007/javaschool
Exemple 17020 - Constructeurs multiples - may be OBSO/src/com/myschool/game/core/Game.java
708
// Fichier Game.java package com.myschool.game.core; public class Game { public static void main(String[] args) { int CharacterCount = 0; Character character1 = new Character("Maxime"); // character1.setLiveScore(10); CharacterCount++; Character character2 = new Character("Alpha", 11); // character2.setLiveScore(11); CharacterCount++; System.out.println("Nombre de personnages : " + CharacterCount); character1.disBonjour(); character2.disBonjour(character1); System.out.println(character1.getName() + " : J'ai " + character1.getLiveScore() + " points de vie!"); System.out.println(character2.getName() + " : J'ai " + character2.getLiveScore() + " points de vie!"); } }
apache-2.0
Rikkola/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-client/kie-wb-common-stunner-widgets/src/main/java/org/kie/workbench/common/stunner/client/widgets/presenters/session/impl/SessionViewerImpl.java
6018
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.stunner.client.widgets.presenters.session.impl; import java.util.function.Supplier; import javax.enterprise.context.Dependent; import javax.inject.Inject; import org.kie.workbench.common.stunner.client.widgets.canvas.ScrollableLienzoPanel; import org.kie.workbench.common.stunner.client.widgets.presenters.diagram.DiagramViewer; import org.kie.workbench.common.stunner.client.widgets.presenters.diagram.impl.AbstractDiagramViewer; import org.kie.workbench.common.stunner.client.widgets.presenters.session.SessionDiagramViewer; import org.kie.workbench.common.stunner.client.widgets.views.WidgetWrapperView; import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas; import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler; import org.kie.workbench.common.stunner.core.client.canvas.Canvas; import org.kie.workbench.common.stunner.core.client.canvas.CanvasPanel; import org.kie.workbench.common.stunner.core.client.canvas.controls.MediatorsControl; import org.kie.workbench.common.stunner.core.client.canvas.controls.SelectionControl; import org.kie.workbench.common.stunner.core.client.preferences.StunnerPreferencesRegistries; import org.kie.workbench.common.stunner.core.client.session.impl.ViewerSession; import org.kie.workbench.common.stunner.core.diagram.Diagram; import org.kie.workbench.common.stunner.core.graph.Element; /** * A generic session's viewer instance. * It aggregates a custom diagram viewer type which provides binds the viewer's diagram instance * to be displayed with the one for the given session. */ @Dependent public class SessionViewerImpl<S extends ViewerSession> extends AbstractSessionViewer<S> implements SessionDiagramViewer<S> { private final AbstractDiagramViewer<Diagram, AbstractCanvasHandler> diagramViewer; private final StunnerPreferencesRegistries preferencesRegistries; private final ScrollableLienzoPanel canvasPanel; private Supplier<Diagram> diagramSupplier; @Inject public SessionViewerImpl(final WidgetWrapperView view, final ScrollableLienzoPanel canvasPanel, final StunnerPreferencesRegistries preferencesRegistries) { this.canvasPanel = canvasPanel; this.preferencesRegistries = preferencesRegistries; this.diagramViewer = new SessionDiagramViewer(view); this.diagramSupplier = () -> null != getSessionHandler() ? getSessionHandler().getDiagram() : null; } public SessionViewerImpl<S> setDiagramSupplier(final Supplier<Diagram> diagramSupplier) { this.diagramSupplier = diagramSupplier; return this; } @Override protected DiagramViewer<Diagram, AbstractCanvasHandler> getDiagramViewer() { return diagramViewer; } @Override protected Diagram getDiagram() { return diagramSupplier.get(); } @Override public void destroy() { super.destroy(); diagramSupplier = null; } @Override @SuppressWarnings("unchecked") public MediatorsControl<AbstractCanvas> getMediatorsControl() { return getSession().getMediatorsControl(); } private S getSession() { return getInstance(); } /** * The internal diagram viewer custom type that binds the diagram(handler to be presented to * the one for the current active sessino. */ private class SessionDiagramViewer extends AbstractDiagramViewer<Diagram, AbstractCanvasHandler> { public SessionDiagramViewer(final WidgetWrapperView view) { super(view); } @Override protected void onOpen(final Diagram diagram) { // The control lifecycle for this diagram editor instance are handled by the session itself. } @Override protected void scalePanel(final int width, final int height) { scale(width, height); } @Override protected void enableControls() { // The control lifecycle for this diagram editor instance are handled by the session itself. } @Override protected void destroyControls() { // The control lifecycle for this diagram editor instance are handled by the session itself. } @Override protected AbstractCanvas getCanvas() { return getSession().getCanvas(); } @Override public CanvasPanel getCanvasPanel() { return canvasPanel; } @Override protected StunnerPreferencesRegistries getPreferencesRegistry() { return preferencesRegistries; } @Override @SuppressWarnings("unchecked") public AbstractCanvasHandler getHandler() { return getSession().getCanvasHandler(); } @Override @SuppressWarnings("unchecked") public <C extends Canvas> MediatorsControl<C> getMediatorsControl() { return (MediatorsControl<C>) getSession().getMediatorsControl(); } @Override @SuppressWarnings("unchecked") public SelectionControl<AbstractCanvasHandler, Element> getSelectionControl() { return getSession().getSelectionControl(); } } }
apache-2.0
approvals/ApprovalTests.Java
approvaltests-util-tests/src/test/java/com/spun/util/WhiteSpaceStripperTest.java
416
package com.spun.util; import org.approvaltests.Approvals; import org.junit.jupiter.api.Test; public class WhiteSpaceStripperTest { @Test public void test() { String[] useCases = {" hello \n \n \n", " hello \r\n \n a \n", " hello "}; Approvals.verifyAll("whitespace", useCases, u -> String.format("---\n%s\n--- ->---\n%s\n---\n", u, WhiteSpaceStripper.stripBlankLines(u))); } }
apache-2.0
huxoll/TopStackCore
src/com/msi/tough/model/EnvironmentBean.java
5599
/* * AvzoneBean.java * * MSI Eucalyptus LoadBalancer Project * Copyright (C) Momentum SI * */ package com.msi.tough.model; import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; /** * Model class for web service object AvailabilityZones. It implements hibernate * entity bean * <p> * Apart from the fields defined in the LoadBalancerDescription following extra * fields are maintained: * <li>id: database generated recored id</li> * </p> * * @author raj * */ @Entity @Table(name = "environment") public class EnvironmentBean { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "user_id") private long userId; @Column(name = "name") private String name; @Column(name = "description") private String desc; @Column(name = "dns_prefix") private String dnsPrefix; @Column(name = "url") private String url; @Column(name = "stack") private String stack; @Column(name = "template") private String template; // TODO add one-to-one relationship back to ApplicationBean @Column(name = "application_name") private String applicationName; @Column(name = "version") private String version; @Column(name = "created_time") private Date createdTime; @Column(name = "updated_time") private Date updatedTime; @Column(name = "status") private String status; @Column(name = "health") private String health; @Column(name = "env_id") private String envId; @Column(name = "resources_stack") private String resourcesStack; @Column(name = "databag") private String databag; @Column(name = "as_group") private String asGroup; @Column(name = "launch_config") private String launchConfig; @Column(name = "loadbalancer") private String loadBalancer; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "env_configs", joinColumns = @JoinColumn(name = "env_id"), inverseJoinColumns = @JoinColumn(name = "config_id")) private Set<ConfigBean> configs; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "env_remove_configs", joinColumns = @JoinColumn(name = "env_id"), inverseJoinColumns = @JoinColumn(name = "config_id")) private Set<ConfigBean> removeConfigs; public String getApplicationName() { return applicationName; } public String getAsGroup() { return asGroup; } public Set<ConfigBean> getConfigs() { return configs; } public Date getCreatedTime() { return createdTime; } public String getDatabag() { return databag; } public String getDesc() { return desc; } public String getDnsPrefix() { return dnsPrefix; } public String getEnvId() { return envId; } public String getHealth() { return health; } public long getId() { return id; } public String getLaunchConfig() { return launchConfig; } public String getLoadBalancer() { return loadBalancer; } public String getName() { return name; } public Set<ConfigBean> getRemoveConfigs() { return removeConfigs; } public String getResourcesStack() { return resourcesStack; } public String getStack() { return stack; } public String getStatus() { return status; } public String getTemplate() { return template; } public Date getUpdatedTime() { return updatedTime; } public String getUrl() { return url; } public long getUserId() { return userId; } public String getVersion() { return version; } public void setApplicationName(final String applicationName) { this.applicationName = applicationName; } public void setAsGroup(final String asGroup) { this.asGroup = asGroup; } public void setConfigs(final Set<ConfigBean> configs) { this.configs = configs; } public void setCreatedTime(final Date createdTime) { this.createdTime = createdTime; } public void setDatabag(final String databag) { this.databag = databag; } public void setDesc(final String desc) { this.desc = desc; } public void setDnsPrefix(final String dnsPrefix) { this.dnsPrefix = dnsPrefix; } public void setEnvId(final String envId) { this.envId = envId; } public void setHealth(final String health) { this.health = health; } public void setId(final long id) { this.id = id; } public void setLaunchConfig(final String launchConfig) { this.launchConfig = launchConfig; } public void setLoadBalancer(final String loadBalancer) { this.loadBalancer = loadBalancer; } public void setName(final String name) { this.name = name; } public void setRemoveConfigs(final Set<ConfigBean> removeConfigs) { this.removeConfigs = removeConfigs; } public void setResourcesStack(final String resourcesStack) { this.resourcesStack = resourcesStack; } public void setStack(final String stack) { this.stack = stack; } public void setStatus(final String status) { this.status = status; } public void setTemplate(final String template) { this.template = template; } public void setUpdatedTime(final Date updatedTime) { this.updatedTime = updatedTime; } public void setUrl(final String url) { this.url = url; } public void setUserId(final long userId) { this.userId = userId; } public void setVersion(final String version) { this.version = version; } }
apache-2.0
cpollet/itinerants
webservice/web/src/main/java/net/cpollet/itinerants/web/rest/resource/AvailabilityController.java
2689
package net.cpollet.itinerants.web.rest.resource; import lombok.extern.slf4j.Slf4j; import net.cpollet.itinerants.core.service.AvailabilityService; import net.cpollet.itinerants.core.service.EventService; import net.cpollet.itinerants.core.service.PersonService; import net.cpollet.itinerants.web.rest.data.AvailabilityPayload; import net.cpollet.itinerants.web.rest.data.AvailabilityResponse; import net.cpollet.itinerants.web.rest.data.EventResponse; import net.cpollet.itinerants.web.rest.data.PersonResponse; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by cpollet on 13.02.17. */ @RestController @RequestMapping("/availabilities") @Slf4j public class AvailabilityController { private static final String AUTHORIZE_OWN_OR_ADMIN = "principal.personId == #availability.personId or hasRole('ADMIN')"; private final AvailabilityService availabilityService; private final PersonService personService; private final EventService eventService; public AvailabilityController(AvailabilityService availabilityService, PersonService personService, EventService eventService) { this.availabilityService = availabilityService; this.personService = personService; this.eventService = eventService; } @PutMapping(value = "") @PreAuthorize(AUTHORIZE_OWN_OR_ADMIN) public AvailabilityResponse create(@RequestBody AvailabilityPayload availability) { log.info("Creating {}", availability); availabilityService.create( AvailabilityService.InputAvailabilityData.delete( availability.getPersonId(), availability.getEventId() ) ); return new AvailabilityResponse( new PersonResponse(personService.getById(availability.getPersonId())), new EventResponse(eventService.getById(availability.getEventId())) ); } @DeleteMapping(value = "") @PreAuthorize(AUTHORIZE_OWN_OR_ADMIN) public void delete(@RequestBody AvailabilityPayload availability) { log.info("Deleting {}", availability); availabilityService.delete( AvailabilityService.InputAvailabilityData.delete( availability.getPersonId(), availability.getEventId() ) ); } }
apache-2.0
googleads/googleads-php-lib
examples/AdManager/v202108/OrderService/UpdateOrders.php
3137
<?php /** * Copyright 2016 Google Inc. All Rights Reserved. * * 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. */ namespace Google\AdsApi\Examples\AdManager\v202108\OrderService; require __DIR__ . '/../../../../vendor/autoload.php'; use Google\AdsApi\AdManager\AdManagerSession; use Google\AdsApi\AdManager\AdManagerSessionBuilder; use Google\AdsApi\AdManager\Util\v202108\StatementBuilder; use Google\AdsApi\AdManager\v202108\ServiceFactory; use Google\AdsApi\Common\OAuth2TokenBuilder; /** * This example updates an array of orders. * * <p>It is meant to be run from a command line (not as a webpage) and requires * that you've setup an `adsapi_php.ini` file in your home directory with your * API credentials and settings. See README.md for more info. */ class UpdateOrders { // Set the ID of the order to update. const ORDER_ID = 'INSERT_ORDER_ID_HERE'; public static function runExample( ServiceFactory $serviceFactory, AdManagerSession $session, int $orderId ) { $orderService = $serviceFactory->createOrderService($session); // Create a statement to only select a single order by ID. $statementBuilder = new StatementBuilder(); $statementBuilder->Where('id = :id'); $statementBuilder->OrderBy('id ASC'); $statementBuilder->Limit(1); $statementBuilder->WithBindVariableValue('id', $orderId); // Get the order. $page = $orderService->getOrdersByStatement( $statementBuilder->toStatement() ); $order = $page->getResults()[0]; // Update the order's notes. $order->setNotes('Spoke to advertiser. All is well.'); // Update the order on the server. $orders = $orderService->updateOrders([$order]); foreach ($orders as $updatedOrder) { printf( "Order with ID %d and name '%s' was updated.%s", $updatedOrder->getId(), $updatedOrder->getName(), PHP_EOL ); } } public static function main() { // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile() ->build(); // Construct an API session configured from an `adsapi_php.ini` file // and the OAuth2 credentials above. $session = (new AdManagerSessionBuilder())->fromFile() ->withOAuth2Credential($oAuth2Credential) ->build(); self::runExample(new ServiceFactory(), $session, self::ORDER_ID); } } UpdateOrders::main();
apache-2.0
kwon37xi/freemarker-dynamic-ql-builder
src/test/java/kr/pe/kwonnam/freemarkerdynamicqlbuilder/objectunwrapper/TemplateModelObjectUnwrapperDefaultImplTest.java
394
package kr.pe.kwonnam.freemarkerdynamicqlbuilder.objectunwrapper; import freemarker.template.Configuration; public class TemplateModelObjectUnwrapperDefaultImplTest extends AbstractTemplateModelObjectUnwrapperTest { @Override protected TemplateModelObjectUnwrapper populateUnwrapper(Configuration configuration) { return new TemplateModelObjectUnwrapperDefaultImpl(); } }
apache-2.0
cdaniel/atlas2
src-ui/map-editor/comment.js
7544
/*jshint esversion: 6 */ var React = require('react'); var _ = require('underscore'); import Actions from './single-map-actions'; import SubmapActions from './dialogs/form-submap/form-a-submap-actions'; import {getStyleForType} from './component-styles'; import {Button, Glyphicon} from 'react-bootstrap'; import {endpointOptions} from './component-styles'; import {actionEndpointOptions} from './component-styles'; import CanvasActions from './canvas-actions'; var LinkContainer = require('react-router-bootstrap').LinkContainer; import ReactResizeDetector from 'react-resize-detector'; var createReactClass = require('create-react-class'); var jsPlumb = require("../../node_modules/jsplumb/dist/js/jsplumb.min.js").jsPlumb; var activeStyle = { boxShadow: "0 0 10px #00789b", color: "#00789b" }; /* globals document */ /* globals window */ function getElementOffset(element) { var de = document.documentElement; var box = element.getBoundingClientRect(); var top = box.top + window.pageYOffset - de.clientTop; var left = box.left + window.pageXOffset - de.clientLeft; return { top: top, left: left }; } var Comment = createReactClass({ getInitialState : function(){ return {focused:false}; }, resizeHandler : function(newWidth) { if(this.resizeHandlerTimeout){ clearTimeout(this.resizeHandlerTimeout); } var id = this.props.id; var mapID = this.props.mapID; var workspaceID = this.props.workspaceID; var updateCall = function(){ Actions.updateComment(workspaceID, mapID, id, null, newWidth); }; this.resizeHandlerTimeout = setTimeout(updateCall,100); }, onClickHandler : function(event){ event.preventDefault(); event.stopPropagation(); if (this.state.hover === "remove") { var id = this.props.id; var mapID = this.props.mapID; var workspaceID = this.props.workspaceID; Actions.deleteComment(workspaceID, mapID, id); return; } if (this.state.hover === "pencil") { var id = this.props.id; //jshint ignore:line var mapID = this.props.mapID; //jshint ignore:line var workspaceID = this.props.workspaceID;//jshint ignore:line Actions.openEditCommentDialog(workspaceID, mapID, id, this.props.comment.text); return; } if (this.state.hover === "group") { SubmapActions.openFormASubmapDialog( this.props.workspaceID, this.props.mapID, this.props.canvasStore.getCanvasState().currentlySelectedNodes, this.props.canvasStore.getCanvasState().currentlySelectedComments); } if((event.nativeEvent.ctrlKey || event.nativeEvent.altKey)){ if (this.props.focused) { CanvasActions.focusRemoveComment(this.props.id); } else { CanvasActions.focusAddComment(this.props.id); } } else if (this.props.focused) { CanvasActions.deselectNodesAndConnections(); } else { CanvasActions.focusComment(this.props.id); } }, mouseOver: function(target) { if(this.props.focused){ this.setState({hover: target}); } }, mouseOut: function(target) { this.setState({hover: null}); }, renderMenu : function(focused){ if (this.input) { jsPlumb.setDraggable(this.input, false); } if (!focused) { return null; } var groupStyle = { position: "absolute", fontSize: "20px", color: "silver", top: "-25px", left: "0px", zIndex: "30" }; if (this.state.hover === "group") { groupStyle = _.extend(groupStyle, activeStyle); } var pencilStyle = { position: "absolute", fontSize: "20px", color: "silver", top: "-25px", left: "0px", zIndex: "30" }; if (this.state.hover === "pencil") { pencilStyle = _.extend(pencilStyle, activeStyle); if (this.input) { jsPlumb.setDraggable(this.input, false); } } var removeStyle = { position: "absolute", color: "silver", top: "-25px", fontSize: "20px", left: "25px", zIndex: "30" }; if (this.state.hover === "remove") { if (this.input) { jsPlumb.setDraggable(this.input, false); } removeStyle = _.extend(removeStyle, activeStyle); } var moveStyle = { position: "absolute", top: "-25px", color: "silver", left: "-25px", fontSize: "20px", zIndex: "30" }; if (this.state.hover === "move") { moveStyle = _.extend(moveStyle, activeStyle); if (this.input) { jsPlumb.setDraggable(this.input, true); } } var menuItems = []; if(this.props.canvasStore.shouldShow("move")){ menuItems.push(<Glyphicon onMouseOver={this.mouseOver.bind(this, "move")} onMouseOut={this.mouseOut} glyph="move" style={moveStyle}></Glyphicon>); } if(this.props.canvasStore.shouldShow("pencil")){ menuItems.push(<Glyphicon onMouseOver={this.mouseOver.bind(this, "pencil")} onMouseOut={this.mouseOut} glyph="pencil" style={pencilStyle}></Glyphicon>); } if(this.props.canvasStore.shouldShow("remove")){ menuItems.push(<Glyphicon onMouseOver={this.mouseOver.bind(this, "remove")} onMouseOut={this.mouseOut} glyph="remove" style={removeStyle}></Glyphicon>); } if(this.props.canvasStore.shouldShow("group")){ menuItems.push(<Glyphicon onMouseOver={this.mouseOver.bind(this, "group")} onMouseOut={this.mouseOut} glyph="resize-small" style={groupStyle}></Glyphicon>); } return ( <div> {menuItems} </div> ); }, render: function() { var comment = this.props.comment; var style = getStyleForType("GenericComment"); var left = comment.x * this.props.size.width; var top = comment.y * this.props.size.height; style = _.extend(style, { left: left, top: top, position: 'absolute', cursor: 'pointer' }); var _this = this; var id = this.props.id; var mapID = this.props.mapID; var txt = comment.text; var focused = this.props.focused; var workspaceID = this.props.workspaceID; var menu = this.renderMenu(focused); var canvasStore = this.props.canvasStore; style.fontSize = canvasStore.getOtherFontSize(); style.padding = style.fontSize / 6 + 'px'; let textStyle = {}; textStyle.width = comment.width ? comment.width + 'px' : '100px'; textStyle.maxWidth = '300px'; if(focused){ textStyle.resize = 'horizontal'; textStyle.overflow = 'auto'; } return ( <div style={style} onClick={this.onClickHandler} id={id} ref={input => { if (input) { this.input = input; } if (!input) { return; } jsPlumb.draggable(input, { containment: true, grid: [ 10, 10 ], stop: function(event) { var offset = getElementOffset(input); var x = offset.left; var y = offset.top; var coords = canvasStore.normalizeComponentCoord({pos : [x,y] }); Actions.updateComment(workspaceID, mapID, id, {x : coords.x,y:coords.y}); } }); }}> <div style={textStyle}>{txt} <ReactResizeDetector handleWidth onResize={this.resizeHandler} /> </div> {menu} </div> ); } }); module.exports = Comment;
apache-2.0
VolodymyrOrlov/tweets-opinion-mining
src/main/scala/com/vorlov/util/Csv.scala
1896
package com.vorlov.util import java.io.File import org.apache.commons.lang3.StringEscapeUtils import scala.annotation.tailrec import scala.io.Source object Csv { abstract class CSVFormat[T] { def asCSVHeader(data: T) = write(data).map(v => s"""${v._1}""").mkString(",") def write(data: T): Iterable[(String, Any)] def read(cells: Seq[String]): T def asCSV(data: T): String = write(data).map(_._2) collect { case s: String => StringEscapeUtils.escapeCsv(s) case v => Option(v) map (_.toString) getOrElse("") } mkString(",") def fromCSV(line: String): T = read(line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)").map(StringEscapeUtils.unescapeCsv)) } implicit class IterableReportFormat[T](iterable: Iterator[T])(implicit format: CSVFormat[T]) extends Iterator[String] { private lazy val firstLine = if(iterable.hasNext) Option(iterable.next()) else None private lazy val header = firstLine.map{ line => Iterator.single{ format.asCSVHeader(line) } ++ Iterator.single{ format.asCSV(line) } } getOrElse(Iterator.empty) override def hasNext: Boolean = header.hasNext || iterable.hasNext override def next(): String = header.hasNext match { case true => header.next case false => format.asCSV(iterable.next) } def asCSV = this } implicit class CsvRichFile[T](file: File)(implicit format: CSVFormat[T]) extends Iterator[T] { private val lines = Source.fromFile(file).getLines() @tailrec private def nextLine(prev: String = ""): String = prev + lines.next() match { case line if (line.count(_ == '"')) % 2 == 0 => line case line => nextLine(line) } val skippedHeader = nextLine() override def hasNext: Boolean = lines.hasNext override def next(): T = format.fromCSV(nextLine()) def asCSV = this } }
apache-2.0
vam-google/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/LicensesListResponse.java
8870
/* * Copyright 2019 Google LLC * * 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 * * https://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 com.google.cloud.compute.v1; import com.google.api.core.BetaApi; import com.google.api.gax.httpjson.ApiMessage; import java.util.LinkedList; import java.util.List; import java.util.Objects; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("by GAPIC") @BetaApi public final class LicensesListResponse implements ApiMessage { private final String id; private final List<License> items; private final String nextPageToken; private final String selfLink; private final Warning warning; private LicensesListResponse() { this.id = null; this.items = null; this.nextPageToken = null; this.selfLink = null; this.warning = null; } private LicensesListResponse( String id, List<License> items, String nextPageToken, String selfLink, Warning warning) { this.id = id; this.items = items; this.nextPageToken = nextPageToken; this.selfLink = selfLink; this.warning = warning; } @Override public Object getFieldValue(String fieldName) { if ("id".equals(fieldName)) { return id; } if ("items".equals(fieldName)) { return items; } if ("nextPageToken".equals(fieldName)) { return nextPageToken; } if ("selfLink".equals(fieldName)) { return selfLink; } if ("warning".equals(fieldName)) { return warning; } return null; } @Nullable @Override public ApiMessage getApiMessageRequestBody() { return null; } @Nullable @Override /** * The fields that should be serialized (even if they have empty values). If the containing * message object has a non-null fieldmask, then all the fields in the field mask (and only those * fields in the field mask) will be serialized. If the containing object does not have a * fieldmask, then only non-empty fields will be serialized. */ public List<String> getFieldMask() { return null; } /** [Output Only] Unique identifier for the resource; defined by the server. */ public String getId() { return id; } /** A list of License resources. */ public List<License> getItemsList() { return items; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. */ public String getNextPageToken() { return nextPageToken; } /** [Output Only] Server-defined URL for this resource. */ public String getSelfLink() { return selfLink; } /** [Output Only] Informational warning message. */ public Warning getWarning() { return warning; } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(LicensesListResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } public static LicensesListResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final LicensesListResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new LicensesListResponse(); } public static class Builder { private String id; private List<License> items; private String nextPageToken; private String selfLink; private Warning warning; Builder() {} public Builder mergeFrom(LicensesListResponse other) { if (other == LicensesListResponse.getDefaultInstance()) return this; if (other.getId() != null) { this.id = other.id; } if (other.getItemsList() != null) { this.items = other.items; } if (other.getNextPageToken() != null) { this.nextPageToken = other.nextPageToken; } if (other.getSelfLink() != null) { this.selfLink = other.selfLink; } if (other.getWarning() != null) { this.warning = other.warning; } return this; } Builder(LicensesListResponse source) { this.id = source.id; this.items = source.items; this.nextPageToken = source.nextPageToken; this.selfLink = source.selfLink; this.warning = source.warning; } /** [Output Only] Unique identifier for the resource; defined by the server. */ public String getId() { return id; } /** [Output Only] Unique identifier for the resource; defined by the server. */ public Builder setId(String id) { this.id = id; return this; } /** A list of License resources. */ public List<License> getItemsList() { return items; } /** A list of License resources. */ public Builder addAllItems(List<License> items) { if (this.items == null) { this.items = new LinkedList<>(); } this.items.addAll(items); return this; } /** A list of License resources. */ public Builder addItems(License items) { if (this.items == null) { this.items = new LinkedList<>(); } this.items.add(items); return this; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. */ public String getNextPageToken() { return nextPageToken; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. */ public Builder setNextPageToken(String nextPageToken) { this.nextPageToken = nextPageToken; return this; } /** [Output Only] Server-defined URL for this resource. */ public String getSelfLink() { return selfLink; } /** [Output Only] Server-defined URL for this resource. */ public Builder setSelfLink(String selfLink) { this.selfLink = selfLink; return this; } /** [Output Only] Informational warning message. */ public Warning getWarning() { return warning; } /** [Output Only] Informational warning message. */ public Builder setWarning(Warning warning) { this.warning = warning; return this; } public LicensesListResponse build() { return new LicensesListResponse(id, items, nextPageToken, selfLink, warning); } public Builder clone() { Builder newBuilder = new Builder(); newBuilder.setId(this.id); newBuilder.addAllItems(this.items); newBuilder.setNextPageToken(this.nextPageToken); newBuilder.setSelfLink(this.selfLink); newBuilder.setWarning(this.warning); return newBuilder; } } @Override public String toString() { return "LicensesListResponse{" + "id=" + id + ", " + "items=" + items + ", " + "nextPageToken=" + nextPageToken + ", " + "selfLink=" + selfLink + ", " + "warning=" + warning + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof LicensesListResponse) { LicensesListResponse that = (LicensesListResponse) o; return Objects.equals(this.id, that.getId()) && Objects.equals(this.items, that.getItemsList()) && Objects.equals(this.nextPageToken, that.getNextPageToken()) && Objects.equals(this.selfLink, that.getSelfLink()) && Objects.equals(this.warning, that.getWarning()); } return false; } @Override public int hashCode() { return Objects.hash(id, items, nextPageToken, selfLink, warning); } }
apache-2.0
pravega/pravega
controller/src/main/java/io/pravega/controller/store/stream/records/HistoryTimeSeriesRecord.java
6640
/** * Copyright Pravega Authors. * * 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 io.pravega.controller.store.stream.records; import com.google.common.collect.ImmutableList; import io.pravega.common.Exceptions; import io.pravega.common.ObjectBuilder; import io.pravega.common.io.serialization.RevisionDataInput; import io.pravega.common.io.serialization.RevisionDataOutput; import io.pravega.common.io.serialization.VersionedSerializer; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.NonNull; import lombok.SneakyThrows; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.Collectors; /** * Each HistoryTimeSeriesRecord captures delta between two consecutive epoch records. * To compute an epoch record from this time series, we need at least one complete epoch record and then we can * apply deltas on it iteratively until we reach the desired epoch record. */ @Data public class HistoryTimeSeriesRecord { public static final HistoryTimeSeriesRecordSerializer SERIALIZER = new HistoryTimeSeriesRecordSerializer(); @Getter private final int epoch; @Getter private final int referenceEpoch; private final ImmutableList<StreamSegmentRecord> segmentsSealed; private final ImmutableList<StreamSegmentRecord> segmentsCreated; @Getter private final long scaleTime; @Builder public HistoryTimeSeriesRecord(int epoch, int referenceEpoch, @NonNull ImmutableList<StreamSegmentRecord> segmentsSealed, @NonNull ImmutableList<StreamSegmentRecord> segmentsCreated, long creationTime) { if (epoch == referenceEpoch) { if (epoch != 0) { Exceptions.checkNotNullOrEmpty(segmentsSealed, "segments sealed"); } Exceptions.checkNotNullOrEmpty(segmentsCreated, "segments created"); } else { Exceptions.checkArgument(segmentsSealed == null || segmentsSealed.isEmpty(), "sealed segments", "should be null for duplicate epoch"); Exceptions.checkArgument(segmentsCreated == null || segmentsCreated.isEmpty(), "created segments", "should be null for duplicate epoch"); } this.epoch = epoch; this.referenceEpoch = referenceEpoch; this.segmentsSealed = segmentsSealed; this.segmentsCreated = segmentsCreated; this.scaleTime = creationTime; } HistoryTimeSeriesRecord(int epoch, int referenceEpoch, long creationTime) { this(epoch, referenceEpoch, ImmutableList.of(), ImmutableList.of(), creationTime); } public boolean isDuplicate() { return epoch != referenceEpoch; } @SneakyThrows(IOException.class) public byte[] toBytes() { return SERIALIZER.serialize(this).getCopy(); } @Override public String toString() { return String.format("%s = %s", "epoch", epoch) + "\n" + String.format("%s = %s", "referenceEpoch", referenceEpoch) + "\n" + String.format("%s = [%n %s%n]", "segmentsSealed", segmentsSealed.stream() .map(streamSegmentRecord -> streamSegmentRecord.toString().replace("\n", "\n ")) .collect(Collectors.joining("\n,\n "))) + "\n" + String.format("%s = [%n %s%n]", "segmentsCreated", segmentsCreated.stream() .map(streamSegmentRecord -> streamSegmentRecord.toString().replace("\n", "\n ")) .collect(Collectors.joining("\n,\n "))) + "\n" + String.format("%s = %s", "scaleTime", scaleTime); } @SneakyThrows(IOException.class) public static HistoryTimeSeriesRecord fromBytes(final byte[] record) { InputStream inputStream = new ByteArrayInputStream(record, 0, record.length); return SERIALIZER.deserialize(inputStream); } private static class HistoryTimeSeriesRecordBuilder implements ObjectBuilder<HistoryTimeSeriesRecord> { } static class HistoryTimeSeriesRecordSerializer extends VersionedSerializer.WithBuilder<HistoryTimeSeriesRecord, HistoryTimeSeriesRecord.HistoryTimeSeriesRecordBuilder> { @Override protected byte getWriteVersion() { return 0; } @Override protected void declareVersions() { version(0).revision(0, this::write00, this::read00); } private void read00(RevisionDataInput revisionDataInput, HistoryTimeSeriesRecord.HistoryTimeSeriesRecordBuilder builder) throws IOException { builder.epoch(revisionDataInput.readInt()) .referenceEpoch(revisionDataInput.readInt()); ImmutableList.Builder<StreamSegmentRecord> sealedSegmentsBuilders = ImmutableList.builder(); revisionDataInput.readCollection(StreamSegmentRecord.SERIALIZER::deserialize, sealedSegmentsBuilders); builder.segmentsSealed(sealedSegmentsBuilders.build()); ImmutableList.Builder<StreamSegmentRecord> segmentsCreatedBuilder = ImmutableList.builder(); revisionDataInput.readCollection(StreamSegmentRecord.SERIALIZER::deserialize, segmentsCreatedBuilder); builder.segmentsCreated(segmentsCreatedBuilder.build()); builder.creationTime(revisionDataInput.readLong()); } private void write00(HistoryTimeSeriesRecord history, RevisionDataOutput revisionDataOutput) throws IOException { revisionDataOutput.writeInt(history.getEpoch()); revisionDataOutput.writeInt(history.getReferenceEpoch()); revisionDataOutput.writeCollection(history.getSegmentsSealed(), StreamSegmentRecord.SERIALIZER::serialize); revisionDataOutput.writeCollection(history.getSegmentsCreated(), StreamSegmentRecord.SERIALIZER::serialize); revisionDataOutput.writeLong(history.getScaleTime()); } @Override protected HistoryTimeSeriesRecord.HistoryTimeSeriesRecordBuilder newBuilder() { return HistoryTimeSeriesRecord.builder(); } } }
apache-2.0
nemecec/protobuf-javame
proto2javame/src/main/java/net/jarlehansen/proto2javame/business/sourcebuilder/publicmethods/PublicMethodsBuilderImpl.java
3189
package net.jarlehansen.proto2javame.business.sourcebuilder.publicmethods; import net.jarlehansen.proto2javame.business.sourcebuilder.resource.CommonResourceConstants; import net.jarlehansen.proto2javame.business.sourcebuilder.resource.JavaSourceCodeUtil; import net.jarlehansen.proto2javame.business.sourcebuilder.resource.ResourceFormatUtil; import net.jarlehansen.proto2javame.domain.proto.FieldData; import net.jarlehansen.proto2javame.domain.proto.ProtoFileInput; import net.jarlehansen.proto2javame.domain.proto.ValidScopes; /** * @author hansjar@gmail.com Jarle Hansen */ public final class PublicMethodsBuilderImpl implements PublicMethodsBuilder { private final ResourceFormatUtil resourceFormat = ResourceFormatUtil.PUBLIC_METHODS; public PublicMethodsBuilderImpl() { } public StringBuilder createPublicMethods(final String className, final ProtoFileInput protoInput) { final StringBuilder builder = new StringBuilder(); builder.append(createGetMethods(protoInput)); builder.append(createToString(protoInput)); return builder; } private String createGetMethods(final ProtoFileInput protoInput) { final StringBuilder builder = new StringBuilder(); for (FieldData field : protoInput.getFields()) { if (field.isList()) { builder.append(resourceFormat.getString(PublicMethodsConstants.KEY_PUBLIC_GETMETHODS, field .getListImpl().getImplementation(), JavaSourceCodeUtil.createCapitalLetterName(field.getName()), field.getName())); } else { builder.append(resourceFormat.getString(PublicMethodsConstants.KEY_PUBLIC_GETMETHODS, field.getType() .getImplementationType(), JavaSourceCodeUtil.createCapitalLetterName(field.getName()), field.getName())); } if (field.getScope() == ValidScopes.OPTIONAL) { builder.append(resourceFormat.getString(PublicMethodsConstants.KEY_PUBLIC_HASMETHODS, JavaSourceCodeUtil.createCapitalLetterName(field.getName()))); } } return builder.toString(); } private String createToString(final ProtoFileInput protoInput) { final StringBuilder builder = new StringBuilder(); builder.append(resourceFormat.getString(PublicMethodsConstants.KEY_PUBLIC_TOSTRING_START)); for (FieldData field : protoInput.getFields()) { if (field.getScope() == ValidScopes.REQUIRED || field.getScope() == ValidScopes.REPEATED) { builder.append(resourceFormat .getString(PublicMethodsConstants.KEY_PUBLIC_TOSTRING_FIELDS, field.getName())); } else { // Must be optional builder.append(resourceFormat .getString(PublicMethodsConstants.KEY_PUBLIC_TOSTRING_FIELDS_OPTIONAL, JavaSourceCodeUtil.createCapitalLetterMethod(field.getName()), field.getName())); } } builder.append(resourceFormat.getString(PublicMethodsConstants.KEY_PUBLIC_TOSTRING_END)); return builder.toString(); } }
apache-2.0
VandyVRC/DIMLI
_php/_homepage/todo_list.php
2830
<?php if(!defined('MAIN_DIR')){define('MAIN_DIR',dirname('__FILENAME__'));} require_once(MAIN_DIR.'/_php/_config/session.php'); require_once(MAIN_DIR.'/_php/_config/connection.php'); require_once(MAIN_DIR.'/_php/_config/functions.php'); confirm_logged_in(); ?> <!-- TO DO LIST FOR CATALOGERS --> <div id="yourOrders"> <h3>To Do</h3> <div id="todo_list" class="defaultCursor"> <?php $sql = "SELECT * FROM $DB_NAME.order WHERE assigned_to = '{$_SESSION['user_id']}' AND (images_catalogued = false OR images_catalogued IS NULL) ORDER BY date_needed, id ASC LIMIT 5 "; $orders = db_query($mysqli, $sql); if ($orders->num_rows <= 0): ?> <div style="max-width: 180px; padding: 15px; font-size: 0.85em; text-align: center; line-height: 1.4em; font-weight: 400;">LUCKY! - you have no assigned work to complete</div> <?php endif; while ($row = $orders->fetch_assoc()): // Fetch export status of this order $sql = "SELECT images_exported FROM $DB_NAME.order WHERE id = {$row['id']} "; $imgs_ava_res = db_query($mysqli, $sql); while ($row_exported = $imgs_ava_res->fetch_assoc()): $imgs_ava = $row_exported['images_exported']; endwhile; $imgs_ava_res->free(); // Fetch all image ids associated with this order $sql = "SELECT legacy_id FROM $DB_NAME.image WHERE order_id = {$row['id']} LIMIT 3 "; $result = db_query($mysqli, $sql); $images = array(); while ($img_row = $result->fetch_assoc()): $images[] = $img_row['legacy_id']; endwhile; ?> <div class="row"> <div class="inner_row thumbnail_previews"> <span class="order_id" data-order="<?php echo $row['id']; ?>">#<?php echo str_pad($row['id'], 4, '0', STR_PAD_LEFT); ?></span> <?php if ($imgs_ava = '1'): ?> <?php foreach ($images as $image): ?> <img src="<?php echo $webroot; ?>/_plugins/timthumb/timthumb.php?src=<?php echo $image_src; echo $image; ?>.jpg&amp;h=28&amp;w=35&amp;q=80"> <?php endforeach; ?> <?php else: ?> <span class="grey" style="margin-left: 10px; font-size: 0.9em;" >Images unavailable</span> <?php endif; ?> </div> <div class="inner_row grey" style="font-size: 0.80em;"> <?php $truncImage = (strlen($image) > 6) ? substr($image, 0, 6) . '...' : $image; echo $row['image_count']. ' image'; echo ($row['image_count'] > 1) ? 's' : ''; echo ', due '.date('l, M j', strtotime($row['date_needed'])); ?> </div> </div> <?php endwhile; ?> </div> </div> <script> $('div#todo_list div.row') .click( function() { var orderNum = $(this).find('span.order_id').attr('data-order'); open_order($.trim(orderNum)); }); </script>
apache-2.0
jonfoster/pyxb1
tests/datatypes/test-hexBinary.py
1256
from pyxb.exceptions_ import * import unittest import pyxb.binding.datatypes as xsd import binascii class Test_hexBinary (unittest.TestCase): def testValues (self): data_values = [ '\x01', '\x00', '\x01\x23', '\x12\x34' ] for dv in data_values: v = xsd.hexBinary(dv) self.assertEqual(v, dv) def testStrings (self): encoded_values = [ u'01', u'00', u'ab', u'Ab', u'AB12' ] for ev in encoded_values: v = xsd.hexBinary.Factory(ev) self.assertEqual(v, ev) v = xsd.hexBinary.Factory(ev, _from_xml=True) self.assertEqual(len(ev)/2, len(v)) self.assertEqual(ev.upper(), v.xsdLiteral()) def testBadStrings (self): self.assertRaises(BadTypeValueError, xsd.hexBinary.Factory, u'0', _from_xml=True) self.assertRaises(BadTypeValueError, xsd.hexBinary.Factory, u'012', _from_xml=True) self.assertRaises(BadTypeValueError, xsd.hexBinary.Factory, u'01s', _from_xml=True) self.assertRaises(BadTypeValueError, xsd.hexBinary.Factory, u'sb', _from_xml=True) def testLiteralization (self): self.assertEqual('', xsd.hexBinary('').xsdLiteral()) if __name__ == '__main__': unittest.main()
apache-2.0
OpenClinica/enketo-express-oc
app/controllers/transformation-controller.js
12093
/** * @module transformation-controller */ const transformer = require( 'enketo-transformer' ); const communicator = require( '../lib/communicator' ); const surveyModel = require( '../models/survey-model' ); const cacheModel = require( '../models/cache-model' ); const account = require( '../models/account-model' ); const user = require( '../models/user-model' ); const config = require( '../models/config-model' ).server; const utils = require( '../lib/utils' ); const routerUtils = require( '../lib/router-utils' ); const express = require( 'express' ); const url = require( 'url' ); const { replaceMediaSources } = require( '../lib/url' ); const router = express.Router(); // var debug = require( 'debug' )( 'transformation-controller' ); module.exports = app => { app.use( `${app.get( 'base path' )}/transform`, router ); }; router.param( 'enketo_id', routerUtils.enketoId ); router.param( 'encrypted_enketo_id_single', routerUtils.encryptedEnketoIdSingle ); router.param( 'encrypted_enketo_id_view', routerUtils.encryptedEnketoIdView ); router.param( 'encrypted_enketo_id_view_dn', routerUtils.encryptedEnketoIdViewDn ); router.param( 'encrypted_enketo_id_view_dnc', routerUtils.encryptedEnketoIdViewDnc ); router.param( 'encrypted_enketo_id_preview', routerUtils.encryptedEnketoIdPreview ); router.param( 'encrypted_enketo_id_fs_c', routerUtils.encryptedEnketoIdFsC ); router.param( 'encrypted_enketo_id_fs_participant', routerUtils.encryptedEnketoIdFsParticipant ); router.param( 'encrypted_enketo_id_full_participant', routerUtils.encryptedEnketoIdFullParticipant ); router.param( 'encrypted_enketo_id_rfc', routerUtils.encryptedEnketoIdEditRfc ); router.param( 'encrypted_enketo_id_rfc_c', routerUtils.encryptedEnketoIdEditRfcC ); router.param( 'encrypted_enketo_id_headless', routerUtils.encryptedEnketoIdEditHeadless ); router .post( '*', ( req, res, next ) => { // set content-type to json to provide appropriate json Error responses res.set( 'Content-Type', 'application/json' ); next(); } ) .post( '/xform/:encrypted_enketo_id_single', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_view', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_preview', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_view_dn', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_view_dnc', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_fs_c', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_rfc', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_rfc_c', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_fs_participant', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_full_participant', getSurveyParts ) .post( '/xform/:encrypted_enketo_id_headless', getSurveyParts ) .post( '/xform/:enketo_id', getSurveyParts ) .post( '/xform', getSurveyParts ) .post( '/xform/hash/:enketo_id', getSurveyHash ) .post( '/xform/hash/:encrypted_enketo_id_full_participant', getSurveyHash ); /** * Obtains HTML Form, XML model, and existing XML instance * * @param {module:api-controller~ExpressRequest} req - HTTP request * @param {module:api-controller~ExpressResponse} res - HTTP response * @param {Function} next - Express callback */ function getSurveyParts( req, res, next ) { _getSurveyParams( req ) .then( survey => { if ( survey.info ) { // A request with "xformUrl" body parameter was used (unlaunched form) _getFormDirectly( survey ) .then( survey => { _respond( res, survey ); } ) .catch( next ); } else { _authenticate( survey ) .then( _getFormFromCache ) .then( result => { if ( result ) { return _updateCache( result ); } else { return _updateCache( survey ); } } ) .then( result => { _respond( res, result ); } ) .catch( next ); } } ) .catch( next ); } /** * Obtains the hash of the cached Survey Parts * * @param {module:api-controller~ExpressRequest} req - HTTP request * @param {module:api-controller~ExpressResponse} res - HTTP response * @param {Function} next - Express callback */ function getSurveyHash( req, res, next ) { _getSurveyParams( req ) .then( survey => cacheModel.getHashes( survey ) ) .then( _updateCache ) .then( survey => { if ( Object.prototype.hasOwnProperty.call( survey, 'credentials' ) ) { delete survey.credentials; } res.status( 200 ); res.send( { hash: _getCombinedHash( survey ) } ); } ) .catch( next ); } /** * @param {module:survey-model~SurveyObject} survey - survey object * * @return { Promise<module:survey-model~SurveyObject> } a Promise resolving with survey object with form transformation result * */ function _getFormDirectly( survey ) { return communicator.getXForm( survey ) .then( _addSettings ) .then( communicator.getManifest ) .then( transformer.transform ); } function _addSettings( survey ) { survey.openclinica = true; return survey; } /** * @param {module:survey-model~SurveyObject} survey - survey object * * @return { Promise<module:survey-model~SurveyObject> } a Promise resolving with survey object */ function _authenticate( survey ) { return communicator.authenticate( survey ); } /** * @param {module:survey-model~SurveyObject} survey - survey object * * @return { Promise<module:survey-model~SurveyObject> } a Promise resolving with survey object */ function _getFormFromCache( survey ) { return cacheModel.get( survey ); } /** * Update the Cache if necessary. * * @param {module:survey-model~SurveyObject} survey - survey object * * @return { Promise<module:survey-model~SurveyObject> } a Promise resolving with survey object */ function _updateCache( survey ) { return communicator.getXFormInfo( survey ) .then( communicator.getManifest ) .then( survey => Promise.all( [ survey, cacheModel.check( survey ) ] ) ) .then( ( [ survey, upToDate ] ) => { if ( !upToDate ) { delete survey.xform; delete survey.form; delete survey.model; delete survey.xslHash; delete survey.mediaHash; delete survey.mediaUrlHash; delete survey.formHash; return _getFormDirectly( survey ) .then( cacheModel.set ); } return survey; } ) .then( _addMediaHash ) .catch( error => { if ( error.status === 401 || error.status === 404 ) { cacheModel.flush( survey ) .catch( e => { if ( e.status !== 404 ) { console.error( e ); } } ); } else { console.error( 'Unknown Error occurred during attempt to update cache', error ); } throw error; } ); } /** * @param {module:survey-model~SurveyObject} survey - survey object * * @return { Promise } always resolved promise * */ function _addMediaHash( survey ) { survey.mediaHash = utils.getXformsManifestHash( survey.manifest, 'all' ); return Promise.resolve( survey ); } /** * @param { module:survey-model~SurveyObject } survey - survey object * * @return { Promise<module:survey-model~SurveyObject> } a Promise resolving with survey object */ function _checkQuota( survey ) { if ( !config['account lib'] ) { // Don't check quota if not running SaaS return Promise.resolve( survey ); } return surveyModel .getNumber( survey.account.linkedServer ) .then( quotaUsed => { if ( quotaUsed <= survey.account.quota ) { return Promise.resolve( survey ); } const error = new Error( 'Forbidden. Quota exceeded.' ); error.status = 403; throw error; } ); } /** * @param {module:api-controller~ExpressResponse} res - HTTP response * @param {module:survey-model~SurveyObject} survey - survey object */ function _respond( res, survey ) { delete survey.credentials; survey = replaceMediaSources( survey ); res.status( 200 ); res.send( { form: survey.form, // previously this was JSON.stringified, not sure why model: survey.model, theme: survey.theme, branding: survey.account.branding, // The hash components are converted to deal with a node_redis limitation with storing and retrieving null. // If a form contains no media this hash is null, which would be an empty string upon first load. // Subsequent cache checks will however get the string value 'null' causing the form cache to be unnecessarily refreshed // on the client. hash: _getCombinedHash( survey ), languageMap: survey.languageMap } ); } /** * @param { module:survey-model~SurveyObject } survey - survey object * @return { string } - a hash */ function _getCombinedHash( survey ) { const FORCE_UPDATE = 1; const brandingHash = ( survey.account.branding && survey.account.branding.source ) ? utils.md5( survey.account.branding.source ) : ''; return [ String( survey.formHash ), String( survey.mediaHash ), String( survey.xslHash ), String( survey.theme ), String( brandingHash ), String( FORCE_UPDATE ) ].join( '-' ); } /** * @param {module:survey-model~SurveyObject} survey - survey object * @param {module:api-controller~ExpressRequest} req - HTTP request * * @return { Promise<module:survey-model~SurveyObject> } a Promise resolving with survey object with added credentials */ function _setCookieAndCredentials( survey, req ) { // for external authentication, pass the cookie(s) survey.cookie = req.headers.cookie; // for OpenRosa authentication, add the credentials survey.credentials = user.getCredentials( req ); return Promise.resolve( survey ); } /** * @param {module:api-controller~ExpressRequest} req - HTTP request * @return { Promise<module:survey-model~SurveyObject> } a Promise resolving with survey object */ function _getSurveyParams( req ) { const params = req.body; const customParamName = req.app.get( 'query parameter to pass to submission' ); const customParam = customParamName ? req.query[ customParamName ] : null; if ( req.enketoId ) { return surveyModel.get( req.enketoId ) .then( account.check ) .then( _checkQuota ) .then( survey => { survey.customParam = customParam; return _setCookieAndCredentials( survey, req ); } ); } else if ( params.xformUrl ) { const urlObj = url.parse( params.xformUrl ); if ( !urlObj || !urlObj.protocol || !urlObj.host ) { const error = new Error( 'Bad Request. Form URL is invalid.' ); error.status = 400; throw error; } const xUrl = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`; return account.check( { openRosaServer: xUrl } ) .then( survey => // no need to check quota Promise.resolve( { info: { downloadUrl: params.xformUrl }, account: survey.account } ) ) .then( survey => _setCookieAndCredentials( survey, req ) ); } else { const error = new Error( 'Bad Request. Survey information not complete.' ); error.status = 400; throw error; } }
apache-2.0
olamy/archiva
archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/archiva/webdav/RepositoryServletProxiedTimestampedSnapshotPolicyTest.java
8924
package org.apache.archiva.webdav; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; import org.apache.archiva.configuration.ProxyConnectorConfiguration; import org.apache.archiva.policies.SnapshotsPolicy; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.ArrayList; /** * RepositoryServlet Tests, Proxied, Get of Timestamped Snapshot Artifacts, with varying policy settings. * * */ public class RepositoryServletProxiedTimestampedSnapshotPolicyTest extends AbstractRepositoryServletProxiedTestCase { @Before public void setup() throws Exception { archivaConfiguration.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() ); super.setUp(); } @After @Override public void tearDown() throws Exception { archivaConfiguration.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() ); super.tearDown(); } @Test public void testGetProxiedSnapshotsArtifactPolicyAlwaysManagedNewer() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_MANAGED_CONTENTS, SnapshotsPolicy.ALWAYS, HAS_MANAGED_COPY, ( NEWER * OVER_ONE_DAY ) ); } @Test public void testGetProxiedSnapshotsArtifactPolicyAlwaysManagedOlder() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.ALWAYS, HAS_MANAGED_COPY, ( OLDER * OVER_ONE_DAY ) ); } @Test public void testGetProxiedSnapshotsArtifactPolicyAlwaysNoManagedContent() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.ALWAYS, NO_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyDailyFail() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_MANAGED_CONTENTS, SnapshotsPolicy.DAILY, HAS_MANAGED_COPY, ( NEWER * ONE_MINUTE ) ); } @Test public void testGetProxiedSnapshotsArtifactPolicyDailyNoManagedContent() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.DAILY, NO_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyDailyPass() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.DAILY, HAS_MANAGED_COPY, ( OLDER * OVER_ONE_DAY ) ); } @Test public void testGetProxiedSnapshotsArtifactPolicyRejectFail() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_MANAGED_CONTENTS, SnapshotsPolicy.NEVER, HAS_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyRejectNoManagedContentFail() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_NOT_FOUND, SnapshotsPolicy.NEVER, NO_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyRejectPass() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_MANAGED_CONTENTS, SnapshotsPolicy.NEVER, HAS_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyHourlyFail() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_MANAGED_CONTENTS, SnapshotsPolicy.HOURLY, HAS_MANAGED_COPY, ( NEWER * ONE_MINUTE ) ); } @Test public void testGetProxiedSnapshotsArtifactPolicyHourlyNoManagedContent() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.HOURLY, NO_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyHourlyPass() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.HOURLY, HAS_MANAGED_COPY, ( OLDER * OVER_ONE_HOUR ) ); } @Test public void testGetProxiedSnapshotsArtifactPolicyOnceFail() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_MANAGED_CONTENTS, SnapshotsPolicy.ONCE, HAS_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyOnceNoManagedContent() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.ONCE, NO_MANAGED_COPY ); } @Test public void testGetProxiedSnapshotsArtifactPolicyOncePass() throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( EXPECT_REMOTE_CONTENTS, SnapshotsPolicy.ONCE, NO_MANAGED_COPY ); } private void assertGetProxiedSnapshotsArtifactWithPolicy( int expectation, String snapshotsPolicy, boolean hasManagedCopy ) throws Exception { assertGetProxiedSnapshotsArtifactWithPolicy( expectation, snapshotsPolicy, hasManagedCopy, 0 ); } private void assertGetProxiedSnapshotsArtifactWithPolicy( int expectation, String snapshotsPolicy, boolean hasManagedCopy, long deltaManagedToRemoteTimestamp ) throws Exception { // --- Setup setupSnapshotsRemoteRepo(); setupCleanInternalRepo(); String resourcePath = "org/apache/archiva/test/3.0-SNAPSHOT/test-3.0-20070822.033400-42.jar"; String expectedRemoteContents = "archiva-test-3.0-20070822.033400-42|jar-remote-contents"; String expectedManagedContents = null; Path remoteFile = populateRepo( remoteSnapshots, resourcePath, expectedRemoteContents ); if ( hasManagedCopy ) { expectedManagedContents = "archiva-test-3.0-20070822.033400-42|jar-managed-contents"; Path managedFile = populateRepo( repoRootInternal, resourcePath, expectedManagedContents ); Files.setLastModifiedTime( managedFile, FileTime.fromMillis( Files.getLastModifiedTime( remoteFile ).toMillis() + deltaManagedToRemoteTimestamp )); } setupSnapshotConnector( REPOID_INTERNAL, remoteSnapshots, snapshotsPolicy ); saveConfiguration(); // --- Execution // process the response code later, not via an exception. //HttpUnitOptions.setExceptionsThrownOnErrorStatus( false ); WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + resourcePath ); WebResponse response = getServletUnitClient().getResponse( request ); // --- Verification switch ( expectation ) { case EXPECT_MANAGED_CONTENTS: assertResponseOK( response ); assertTrue( "Invalid Test Case: Can't expect managed contents with " + "test that doesn't have a managed copy in the first place.", hasManagedCopy ); assertEquals( "Expected managed file contents", expectedManagedContents, response.getContentAsString() ); break; case EXPECT_REMOTE_CONTENTS: assertResponseOK( response ); assertEquals( "Expected remote file contents", expectedRemoteContents, response.getContentAsString() ); break; case EXPECT_NOT_FOUND: assertResponseNotFound( response ); assertManagedFileNotExists( repoRootInternal, resourcePath ); break; } } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-autoscaling/src/main/java/com/amazonaws/services/autoscaling/model/CustomizedMetricSpecification.java
13722
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.autoscaling.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Represents a CloudWatch metric of your choosing for a target tracking scaling policy to use with Amazon EC2 Auto * Scaling. * </p> * <p> * To create your customized metric specification: * </p> * <ul> * <li> * <p> * Add values for each required parameter from CloudWatch. You can use an existing metric, or a new metric that you * create. To use your own metric, you must first publish the metric to CloudWatch. For more information, see <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html">Publish Custom * Metrics</a> in the <i>Amazon CloudWatch User Guide</i>. * </p> * </li> * <li> * <p> * Choose a metric that changes proportionally with capacity. The value of the metric should increase or decrease in * inverse proportion to the number of capacity units. That is, the value of the metric should decrease when capacity * increases. * </p> * </li> * </ul> * <p> * For more information about CloudWatch, see <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html">Amazon CloudWatch * Concepts</a>. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/CustomizedMetricSpecification" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CustomizedMetricSpecification implements Serializable, Cloneable { /** * <p> * The name of the metric. * </p> */ private String metricName; /** * <p> * The namespace of the metric. * </p> */ private String namespace; /** * <p> * The dimensions of the metric. * </p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your scaling * policy. * </p> */ private com.amazonaws.internal.SdkInternalList<MetricDimension> dimensions; /** * <p> * The statistic of the metric. * </p> */ private String statistic; /** * <p> * The unit of the metric. * </p> */ private String unit; /** * <p> * The name of the metric. * </p> * * @param metricName * The name of the metric. */ public void setMetricName(String metricName) { this.metricName = metricName; } /** * <p> * The name of the metric. * </p> * * @return The name of the metric. */ public String getMetricName() { return this.metricName; } /** * <p> * The name of the metric. * </p> * * @param metricName * The name of the metric. * @return Returns a reference to this object so that method calls can be chained together. */ public CustomizedMetricSpecification withMetricName(String metricName) { setMetricName(metricName); return this; } /** * <p> * The namespace of the metric. * </p> * * @param namespace * The namespace of the metric. */ public void setNamespace(String namespace) { this.namespace = namespace; } /** * <p> * The namespace of the metric. * </p> * * @return The namespace of the metric. */ public String getNamespace() { return this.namespace; } /** * <p> * The namespace of the metric. * </p> * * @param namespace * The namespace of the metric. * @return Returns a reference to this object so that method calls can be chained together. */ public CustomizedMetricSpecification withNamespace(String namespace) { setNamespace(namespace); return this; } /** * <p> * The dimensions of the metric. * </p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your scaling * policy. * </p> * * @return The dimensions of the metric.</p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your * scaling policy. */ public java.util.List<MetricDimension> getDimensions() { if (dimensions == null) { dimensions = new com.amazonaws.internal.SdkInternalList<MetricDimension>(); } return dimensions; } /** * <p> * The dimensions of the metric. * </p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your scaling * policy. * </p> * * @param dimensions * The dimensions of the metric.</p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your * scaling policy. */ public void setDimensions(java.util.Collection<MetricDimension> dimensions) { if (dimensions == null) { this.dimensions = null; return; } this.dimensions = new com.amazonaws.internal.SdkInternalList<MetricDimension>(dimensions); } /** * <p> * The dimensions of the metric. * </p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your scaling * policy. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setDimensions(java.util.Collection)} or {@link #withDimensions(java.util.Collection)} if you want to * override the existing values. * </p> * * @param dimensions * The dimensions of the metric.</p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your * scaling policy. * @return Returns a reference to this object so that method calls can be chained together. */ public CustomizedMetricSpecification withDimensions(MetricDimension... dimensions) { if (this.dimensions == null) { setDimensions(new com.amazonaws.internal.SdkInternalList<MetricDimension>(dimensions.length)); } for (MetricDimension ele : dimensions) { this.dimensions.add(ele); } return this; } /** * <p> * The dimensions of the metric. * </p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your scaling * policy. * </p> * * @param dimensions * The dimensions of the metric.</p> * <p> * Conditional: If you published your metric with dimensions, you must specify the same dimensions in your * scaling policy. * @return Returns a reference to this object so that method calls can be chained together. */ public CustomizedMetricSpecification withDimensions(java.util.Collection<MetricDimension> dimensions) { setDimensions(dimensions); return this; } /** * <p> * The statistic of the metric. * </p> * * @param statistic * The statistic of the metric. * @see MetricStatistic */ public void setStatistic(String statistic) { this.statistic = statistic; } /** * <p> * The statistic of the metric. * </p> * * @return The statistic of the metric. * @see MetricStatistic */ public String getStatistic() { return this.statistic; } /** * <p> * The statistic of the metric. * </p> * * @param statistic * The statistic of the metric. * @return Returns a reference to this object so that method calls can be chained together. * @see MetricStatistic */ public CustomizedMetricSpecification withStatistic(String statistic) { setStatistic(statistic); return this; } /** * <p> * The statistic of the metric. * </p> * * @param statistic * The statistic of the metric. * @see MetricStatistic */ public void setStatistic(MetricStatistic statistic) { withStatistic(statistic); } /** * <p> * The statistic of the metric. * </p> * * @param statistic * The statistic of the metric. * @return Returns a reference to this object so that method calls can be chained together. * @see MetricStatistic */ public CustomizedMetricSpecification withStatistic(MetricStatistic statistic) { this.statistic = statistic.toString(); return this; } /** * <p> * The unit of the metric. * </p> * * @param unit * The unit of the metric. */ public void setUnit(String unit) { this.unit = unit; } /** * <p> * The unit of the metric. * </p> * * @return The unit of the metric. */ public String getUnit() { return this.unit; } /** * <p> * The unit of the metric. * </p> * * @param unit * The unit of the metric. * @return Returns a reference to this object so that method calls can be chained together. */ public CustomizedMetricSpecification withUnit(String unit) { setUnit(unit); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMetricName() != null) sb.append("MetricName: ").append(getMetricName()).append(","); if (getNamespace() != null) sb.append("Namespace: ").append(getNamespace()).append(","); if (getDimensions() != null) sb.append("Dimensions: ").append(getDimensions()).append(","); if (getStatistic() != null) sb.append("Statistic: ").append(getStatistic()).append(","); if (getUnit() != null) sb.append("Unit: ").append(getUnit()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CustomizedMetricSpecification == false) return false; CustomizedMetricSpecification other = (CustomizedMetricSpecification) obj; if (other.getMetricName() == null ^ this.getMetricName() == null) return false; if (other.getMetricName() != null && other.getMetricName().equals(this.getMetricName()) == false) return false; if (other.getNamespace() == null ^ this.getNamespace() == null) return false; if (other.getNamespace() != null && other.getNamespace().equals(this.getNamespace()) == false) return false; if (other.getDimensions() == null ^ this.getDimensions() == null) return false; if (other.getDimensions() != null && other.getDimensions().equals(this.getDimensions()) == false) return false; if (other.getStatistic() == null ^ this.getStatistic() == null) return false; if (other.getStatistic() != null && other.getStatistic().equals(this.getStatistic()) == false) return false; if (other.getUnit() == null ^ this.getUnit() == null) return false; if (other.getUnit() != null && other.getUnit().equals(this.getUnit()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMetricName() == null) ? 0 : getMetricName().hashCode()); hashCode = prime * hashCode + ((getNamespace() == null) ? 0 : getNamespace().hashCode()); hashCode = prime * hashCode + ((getDimensions() == null) ? 0 : getDimensions().hashCode()); hashCode = prime * hashCode + ((getStatistic() == null) ? 0 : getStatistic().hashCode()); hashCode = prime * hashCode + ((getUnit() == null) ? 0 : getUnit().hashCode()); return hashCode; } @Override public CustomizedMetricSpecification clone() { try { return (CustomizedMetricSpecification) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
langbat/webservice
index.php
6382
<?php //print_r($_SERVER);die; /* *--------------------------------------------------------------- * APPLICATION ENVIRONMENT *--------------------------------------------------------------- * * You can load different configurations depending on your * current environment. Setting the environment also influences * things like logging and error reporting. * * This can be set to anything, but default usage is: * * development * testing * production * * NOTE: If you change these, also change the error_reporting() code below * */ define('ENVIRONMENT', 'development'); /* *--------------------------------------------------------------- * ERROR REPORTING *--------------------------------------------------------------- * * Different environments will require different levels of error reporting. * By default development will show errors but testing and live will hide them. */ if (defined('ENVIRONMENT')) { switch (ENVIRONMENT) { case 'development': error_reporting(E_ALL); break; case 'testing': case 'production': error_reporting(0); break; default: exit('The application environment is not set correctly.'); } } /* *--------------------------------------------------------------- * SYSTEM FOLDER NAME *--------------------------------------------------------------- * * This variable must contain the name of your "system" folder. * Include the path if the folder is not in the same directory * as this file. * */ $system_path = 'system'; /* *--------------------------------------------------------------- * APPLICATION FOLDER NAME *--------------------------------------------------------------- * * If you want this front controller to use a different "application" * folder then the default one you can set its name here. The folder * can also be renamed or relocated anywhere on your server. If * you do, use a full server path. For more info please see the user guide: * http://codeigniter.com/user_guide/general/managing_apps.html * * NO TRAILING SLASH! * */ $application_folder = 'application'; /* * -------------------------------------------------------------------- * DEFAULT CONTROLLER * -------------------------------------------------------------------- * * Normally you will set your default controller in the routes.php file. * You can, however, force a custom routing by hard-coding a * specific controller class/function here. For most applications, you * WILL NOT set your routing here, but it's an option for those * special instances where you might want to override the standard * routing in a specific front controller that shares a common CI installation. * * IMPORTANT: If you set the routing here, NO OTHER controller will be * callable. In essence, this preference limits your application to ONE * specific controller. Leave the function name blank if you need * to call functions dynamically via the URI. * * Un-comment the $routing array below to use this feature * */ // The directory name, relative to the "controllers" folder. Leave blank // if your controller is not in a sub-folder within the "controllers" folder // $routing['directory'] = ''; // The controller class file name. Example: Mycontroller // $routing['controller'] = ''; // The controller function you wish to be called. // $routing['function'] = ''; /* * ------------------------------------------------------------------- * CUSTOM CONFIG VALUES * ------------------------------------------------------------------- * * The $assign_to_config array below will be passed dynamically to the * config class when initialized. This allows you to set custom config * items or override any default config values found in the config.php file. * This can be handy as it permits you to share one application between * multiple front controller files, with each file containing different * config values. * * Un-comment the $assign_to_config array below to use this feature * */ // $assign_to_config['name_of_config_item'] = 'value of config item'; // -------------------------------------------------------------------- // END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE // -------------------------------------------------------------------- /* * --------------------------------------------------------------- * Resolve the system path for increased reliability * --------------------------------------------------------------- */ // Set the current directory correctly for CLI requests if (defined('STDIN')) { chdir(dirname(__FILE__)); } if (realpath($system_path) !== FALSE) { $system_path = realpath($system_path).'/'; } // ensure there's a trailing slash $system_path = rtrim($system_path, '/').'/'; // Is the system path correct? if ( ! is_dir($system_path)) { exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME)); } /* * ------------------------------------------------------------------- * Now that we know the path, set the main path constants * ------------------------------------------------------------------- */ // The name of THIS file define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); // The PHP file extension // this global constant is deprecated. define('EXT', '.php'); // Path to the system folder define('BASEPATH', str_replace("\\", "/", $system_path)); // Path to the front controller (this file) define('FCPATH', str_replace(SELF, '', __FILE__)); // Name of the "system folder" define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/')); // The path to the "application" folder if (is_dir($application_folder)) { define('APPPATH', $application_folder.'/'); } else { if ( ! is_dir(BASEPATH.$application_folder.'/')) { exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF); } define('APPPATH', BASEPATH.$application_folder.'/'); } /* * -------------------------------------------------------------------- * LOAD THE BOOTSTRAP FILE * -------------------------------------------------------------------- * * And away we go... * */ require_once BASEPATH.'core/CodeIgniter.php'; /* End of file index.php */ /* Location: ./index.php */
apache-2.0
enr1c091/conv-ret-rank
src/main/webapp/dist/js/dialog.response.js
2466
System.register([], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var DialogResponse; return { setters:[], execute: function() { /** * (C) Copyright IBM Corp. 2016. All Rights Reserved. * * 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. */ /* * This class is responsible for storing Dialog service class's response payload. */ DialogResponse = (function () { function DialogResponse(text, user, ce, payload) { this.arr = []; this.user = user; this.text = text; this.ce = ce; if (ce) { this.arr = []; for (var i = 0; i < ce.length; i++) { this.arr.push({ body: ce[i].body, confidence: ce[i].confidence, highlight: ce[i].highlight, sourceUrl: ce[i].sourceUrl, title: ce[i].title }); } } this.payload = payload; } DialogResponse.prototype.getText = function () { return this.text; }; DialogResponse.prototype.isUser = function () { return this.user; }; DialogResponse.prototype.getCe = function () { return this.arr; }; DialogResponse.prototype.getPayload = function () { return this.payload; }; return DialogResponse; }()); exports_1("DialogResponse", DialogResponse); } } }); //# sourceMappingURL=dialog.response.js.map
apache-2.0
yippeesoft/NotifyTools
cplussharp/vscode/rusttest/ncnntengine2rs/build.rs
1060
extern crate bindgen; // extern crate cc; use std::env; use std::path::PathBuf; fn main() { let lib_path = PathBuf::from(env::current_dir().unwrap().join(".")); println!("cargo:rustc-link-search={}", lib_path.display()); println!("cargo:rustc-link-lib=tengine-lite"); // println!("cargo:rustc-link-lib=ncnn"); let bindingsncnn = bindgen::Builder::default() .header("c_api.h") // .whitelist_function("hello_from_c") .generate() .expect("unable to generate hello bindings"); // let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindingsncnn.write_to_file("ncnn_c_api.rs") .expect("couldn't write bindings!"); let bindingsten = bindgen::Builder::default() .header("tengine_c_api.h") // .whitelist_function("hello_from_c") .generate() .expect("unable to generate hello bindings"); // let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindingsten.write_to_file("tengine_c_api.rs") .expect("couldn't write bindings!"); }
apache-2.0
burtcorp/amphtml
test/functional/test-performance.js
20076
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * 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. */ import { installPerformanceService, performanceFor, } from '../../src/service/performance-impl'; import {resourcesForDoc} from '../../src/resources'; import {viewerForDoc} from '../../src/viewer'; import * as lolex from 'lolex'; import {getMode} from '../../src/mode'; describes.realWin('performance', {amp: true}, env => { let sandbox; let perf; let clock; let win; let ampdoc; beforeEach(() => { win = env.win; sandbox = env.sandbox; ampdoc = env.ampdoc; clock = lolex.install(win, 0, ['Date', 'setTimeout', 'clearTimeout']); installPerformanceService(env.win); perf = performanceFor(env.win); }); describe('when viewer is not ready', () => { it('should queue up tick events', () => { expect(perf.events_.length).to.equal(0); perf.tick('start'); expect(perf.events_.length).to.equal(1); perf.tick('startEnd'); expect(perf.events_.length).to.equal(2); }); it('should map tickDelta to tick', () => { expect(perf.events_.length).to.equal(0); perf.tickDelta('test', 99); expect(perf.events_.length).to.equal(1); expect(perf.events_[0]) .to.be.jsonEqual({ label: 'test', delta: 99, }); }); it('should have max 50 queued events', () => { expect(perf.events_.length).to.equal(0); for (let i = 0; i < 200; i++) { perf.tick(`start${i}`); } expect(perf.events_.length).to.equal(50); }); it('should add default optional relative start time on the ' + 'queued tick event', () => { clock.tick(150); perf.tick('start0'); expect(perf.events_[0]).to.be.jsonEqual({ label: 'start0', value: 150, }); }); it('should drop events in the head of the queue', () => { const tickTime = 100; clock.tick(tickTime); expect(perf.events_.length).to.equal(0); for (let i = 0; i < 50 ; i++) { perf.tick(`start${i}`); } expect(perf.events_.length).to.equal(50); expect(perf.events_[0]).to.be.jsonEqual({ label: 'start0', value: tickTime, }); clock.tick(1); perf.tick('start50'); expect(perf.events_[0]).to.be.jsonEqual({ label: 'start1', value: tickTime, }); expect(perf.events_[49]).to.be.jsonEqual({ label: 'start50', value: tickTime + 1, }); }); }); describe('when viewer is ready,', () => { let viewer; let viewerSendMessageStub; beforeEach(() => { viewer = viewerForDoc(ampdoc); viewerSendMessageStub = sandbox.stub(viewer, 'sendMessage'); }); describe('config', () => { it('should configure correctly when viewer is embedded and supports ' + 'csi', () => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns('1'); sandbox.stub(viewer, 'isEmbedded').returns(true); perf.coreServicesAvailable().then(() => { expect(perf.isPerformanceTrackingOn()).to.be.true; }); }); it('should configure correctly when viewer is embedded and does ' + 'NOT support csi', () => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns('0'); sandbox.stub(viewer, 'isEmbedded').returns(true); perf.coreServicesAvailable().then(() => { expect(perf.isPerformanceTrackingOn()).to.be.false; }); }); it('should configure correctly when viewer is embedded and does ' + 'NOT support csi', () => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns(null); sandbox.stub(viewer, 'isEmbedded').returns(true); perf.coreServicesAvailable().then(() => { expect(perf.isPerformanceTrackingOn()).to.be.false; }); }); it('should configure correctly when viewer is not embedded', () => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns(null); sandbox.stub(viewer, 'isEmbedded').returns(false); perf.coreServicesAvailable().then(() => { expect(perf.isPerformanceTrackingOn()).to.be.false; }); }); }); describe('channel established', () => { it('should flush events when channel is ready', () => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns(null); sandbox.stub(viewer, 'whenMessagingReady') .returns(Promise.resolve()); expect(perf.isMessagingReady_).to.be.false; const promise = perf.coreServicesAvailable(); expect(perf.events_.length).to.equal(0); perf.tick('start'); expect(perf.events_.length).to.equal(1); perf.tick('startEnd'); expect(perf.events_.length).to.equal(2); expect(perf.isMessagingReady_).to.be.false; const flushSpy = sandbox.spy(perf, 'flush'); expect(flushSpy).to.have.callCount(0); perf.flush(); expect(flushSpy).to.have.callCount(1); expect(perf.events_.length).to.equal(2); return promise.then(() => { expect(perf.isMessagingReady_).to.be.true; expect(flushSpy).to.have.callCount(4); expect(perf.events_.length).to.equal(0); }); }); }); describe('channel not established', () => { it('should not flush anything', () => { sandbox.stub(viewer, 'whenMessagingReady').returns(null); expect(perf.isMessagingReady_).to.be.false; expect(perf.events_.length).to.equal(0); perf.tick('start'); expect(perf.events_.length).to.equal(1); perf.tick('startEnd'); expect(perf.events_.length).to.equal(2); expect(perf.isMessagingReady_).to.be.false; const flushSpy = sandbox.spy(perf, 'flush'); expect(flushSpy).to.have.callCount(0); perf.flush(); expect(flushSpy).to.have.callCount(1); expect(perf.events_.length).to.equal(2); return perf.coreServicesAvailable().then(() => { expect(flushSpy).to.have.callCount(3); expect(perf.isMessagingReady_).to.be.false; expect(perf.events_.length).to.equal(4); }); }); }); describe('tickSinceVisible', () => { let tickDeltaStub; let firstVisibleTime; beforeEach(() => { tickDeltaStub = sandbox.stub(perf, 'tickDelta'); firstVisibleTime = null; sandbox.stub(viewer, 'getFirstVisibleTime', () => firstVisibleTime); }); it('should always be zero before viewer is set', () => { clock.tick(10); perf.tickSinceVisible('test'); expect(tickDeltaStub).to.have.been.calledOnce; expect(tickDeltaStub.firstCall.args[1]).to.equal(0); }); it('should always be zero before visible', () => { perf.coreServicesAvailable(); clock.tick(10); perf.tickSinceVisible('test'); expect(tickDeltaStub).to.have.been.calledOnce; expect(tickDeltaStub.firstCall.args[1]).to.equal(0); }); it('should calculate after visible', () => { perf.coreServicesAvailable(); firstVisibleTime = 5; clock.tick(10); perf.tickSinceVisible('test'); expect(tickDeltaStub).to.have.been.calledOnce; expect(tickDeltaStub.firstCall.args[1]).to.equal(5); }); it('should be zero after visible but for earlier event', () => { perf.coreServicesAvailable(); firstVisibleTime = 5; // An earlier event, since event time (4) is less than visible time (5). clock.tick(4); perf.tickSinceVisible('test'); expect(tickDeltaStub).to.have.been.calledOnce; expect(tickDeltaStub.firstCall.args[1]).to.equal(0); }); }); describe('and performanceTracking is off', () => { beforeEach(() => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns(null); sandbox.stub(viewer, 'isEmbedded').returns(false); }); it('should not forward queued ticks', () => { perf.tick('start0'); clock.tick(1); perf.tick('start1', 'start0'); expect(perf.events_.length).to.equal(2); return perf.coreServicesAvailable().then(() => { perf.flushQueuedTicks_(); perf.flush(); expect(perf.events_.length).to.equal(0); expect(viewerSendMessageStub.withArgs('tick')).to.not.be.called; expect(viewerSendMessageStub.withArgs('sendCsi', undefined, /* cancelUnsent */true)).to.not.be.called; }); }); it('should ignore all calls to tick', () => { perf.tick('start0'); return perf.coreServicesAvailable().then(() => { expect(viewerSendMessageStub.withArgs('tick')).to.not.be.called; }); }); it('should ignore all calls to flush', () => { perf.tick('start0'); perf.flush(); return perf.coreServicesAvailable().then(() => { expect(viewerSendMessageStub.withArgs('sendCsi', undefined, /* cancelUnsent */true)).to.not.be.called; }); }); }); describe('and performanceTracking is on', () => { beforeEach(() => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns('1'); sandbox.stub(viewer, 'isEmbedded').returns(true); sandbox.stub(viewer, 'whenMessagingReady') .returns(Promise.resolve()); }); it('should forward all queued tick events', () => { perf.tick('start0'); clock.tick(1); perf.tick('start1'); expect(perf.events_.length).to.equal(2); return perf.coreServicesAvailable().then(() => { expect(viewerSendMessageStub.withArgs('tick').getCall(0).args[1]) .to.be.jsonEqual({ label: 'start0', value: 0, }); expect(viewerSendMessageStub.withArgs('tick').getCall(1).args[1]) .to.be.jsonEqual({ label: 'start1', value: 1, }); }); }); it('should have no more queued tick events after flush', () => { perf.tick('start0'); perf.tick('start1'); expect(perf.events_.length).to.equal(2); return perf.coreServicesAvailable().then(() => { expect(perf.events_.length).to.equal(0); }); }); it('should forward tick events', () => { return perf.coreServicesAvailable().then(() => { clock.tick(100); perf.tick('start0'); perf.tick('start1', 300); expect(viewerSendMessageStub.withArgs('tick').getCall(2).args[1]) .to.be.jsonEqual({ label: 'start0', value: 100, }); expect(viewerSendMessageStub.withArgs('tick').getCall(3).args[1]) .to.be.jsonEqual({ label: 'start1', delta: 300, }); }); }); it('should call the flush callback', () => { const payload = { ampexp: getMode(win).rtvVersion, }; expect(viewerSendMessageStub.withArgs('sendCsi', payload, /* cancelUnsent */true)).to.have.callCount(0); // coreServicesAvailable calls flush once. return perf.coreServicesAvailable().then(() => { expect(viewerSendMessageStub.withArgs('sendCsi', payload, /* cancelUnsent */true)).to.have.callCount(1); perf.flush(); expect(viewerSendMessageStub.withArgs('sendCsi', payload, /* cancelUnsent */true)).to.have.callCount(2); perf.flush(); expect(viewerSendMessageStub.withArgs('sendCsi', payload, /* cancelUnsent */true)).to.have.callCount(3); }); }); }); }); // TODO(dvoytenko, #7815): re-enable once the reporting regression is // confirmed. it.skip('should wait for visible resources', () => { function resource() { const res = { loadedComplete: false, }; res.loadedOnce = () => Promise.resolve().then(() => { res.loadedComplete = true; }); return res; } const resources = resourcesForDoc(ampdoc); const resourcesMock = sandbox.mock(resources); perf.resources_ = resources; const res1 = resource(); const res2 = resource(); resourcesMock .expects('getResourcesInRect') .withExactArgs( perf.win, sinon.match(arg => arg.left == 0 && arg.top == 0 && arg.width == perf.win.innerWidth && arg.height == perf.win.innerHeight), /* inPrerender */ true) .returns(Promise.resolve([res1, res2])) .once(); return perf.whenViewportLayoutComplete_().then(() => { expect(res1.loadedComplete).to.be.true; expect(res2.loadedComplete).to.be.true; }); }); describe('coreServicesAvailable', () => { let tickSpy; let viewer; let viewerSendMessageStub; let whenFirstVisiblePromise; let whenFirstVisibleResolve; let whenViewportLayoutCompletePromise; let whenViewportLayoutCompleteResolve; function stubHasBeenVisible(visibility) { sandbox.stub(viewer, 'hasBeenVisible') .returns(visibility); } beforeEach(() => { viewer = viewerForDoc(ampdoc); sandbox.stub(viewer, 'whenMessagingReady') .returns(Promise.resolve()); viewerSendMessageStub = sandbox.stub(viewer, 'sendMessage'); tickSpy = sandbox.spy(perf, 'tick'); whenFirstVisiblePromise = new Promise(resolve => { whenFirstVisibleResolve = resolve; }); whenViewportLayoutCompletePromise = new Promise(resolve => { whenViewportLayoutCompleteResolve = resolve; }); sandbox.stub(viewer, 'whenFirstVisible') .returns(whenFirstVisiblePromise); // TODO(dvoytenko, #7815): switch back to the non-legacy version once the // reporting regression is confirmed. sandbox.stub(perf, 'whenViewportLayoutCompleteLegacy_') .returns(whenViewportLayoutCompletePromise); sandbox.stub(perf, 'whenViewportLayoutComplete_') .returns(whenViewportLayoutCompletePromise); return viewer.whenMessagingReady(); }); describe('document started in prerender', () => { beforeEach(() => { clock.tick(100); stubHasBeenVisible(false); return perf.coreServicesAvailable(); }); it('should call prerenderComplete on viewer', () => { clock.tick(100); whenFirstVisibleResolve(); sandbox.stub(viewer, 'getParam').withArgs('csi').returns('1'); sandbox.stub(viewer, 'isEmbedded').returns(true); return viewer.whenFirstVisible().then(() => { clock.tick(400); whenViewportLayoutCompleteResolve(); return perf.whenViewportLayoutComplete_().then(() => { expect(viewerSendMessageStub.withArgs( 'prerenderComplete').firstCall.args[1].value).to.equal(400); }); }); }); it('should call prerenderComplete on viewer even if csi is ' + 'off', () => { clock.tick(100); whenFirstVisibleResolve(); sandbox.stub(viewer, 'getParam').withArgs('csi').returns(null); return viewer.whenFirstVisible().then(() => { clock.tick(400); whenViewportLayoutCompleteResolve(); return perf.whenViewportLayoutComplete_().then(() => { expect(viewerSendMessageStub.withArgs( 'prerenderComplete').firstCall.args[1].value).to.equal(400); }); }); }); it('should tick `pc` with delta=400 when user request document ' + 'to be visible before before first viewport completion', () => { clock.tick(100); whenFirstVisibleResolve(); expect(tickSpy).to.have.callCount(1); return viewer.whenFirstVisible().then(() => { clock.tick(400); expect(tickSpy).to.have.callCount(2); whenViewportLayoutCompleteResolve(); return perf.whenViewportLayoutComplete_().then(() => { expect(tickSpy).to.have.callCount(3); expect(tickSpy.getCall(1).args[0]).to.equal('ofv'); expect(tickSpy.getCall(2).args[0]).to.equal('pc'); expect(Number(tickSpy.getCall(2).args[1])).to.equal(400); }); }); }); it('should tick `pc` with `delta=1` when viewport is complete ' + 'before user request document to be visible', () => { clock.tick(300); whenViewportLayoutCompleteResolve(); return perf.whenViewportLayoutComplete_().then(() => { expect(tickSpy).to.have.callCount(2); expect(tickSpy.firstCall.args[0]).to.equal('ol'); expect(tickSpy.secondCall.args[0]).to.equal('pc'); expect(Number(tickSpy.secondCall.args[1])).to.equal(1); }); }); }); describe('document did not start in prerender', () => { beforeEach(() => { stubHasBeenVisible(true); perf.coreServicesAvailable(); }); it('should call prerenderComplete on viewer', () => { sandbox.stub(viewer, 'getParam').withArgs('csi').returns('1'); sandbox.stub(viewer, 'isEmbedded').returns(true); clock.tick(300); whenViewportLayoutCompleteResolve(); return perf.whenViewportLayoutComplete_().then(() => { expect(viewerSendMessageStub.withArgs( 'prerenderComplete').firstCall.args[1].value).to.equal(300); }); }); it('should tick `pc` with `opt_value=undefined` when user requests ' + 'document to be visible', () => { clock.tick(300); whenViewportLayoutCompleteResolve(); return perf.whenViewportLayoutComplete_().then(() => { expect(tickSpy).to.have.callCount(2); expect(tickSpy.firstCall.args[0]).to.equal('ol'); expect(tickSpy.secondCall.args[0]).to.equal('pc'); expect(tickSpy.secondCall.args[2]).to.be.undefined; }); }); }); }); }); describes.realWin('performance with experiment', {amp: true}, env => { let win; let perf; let viewerSendMessageStub; let sandbox; beforeEach(() => { win = env.win; sandbox = env.sandbox; const viewer = viewerForDoc(env.ampdoc); viewerSendMessageStub = sandbox.stub(viewer, 'sendMessage'); sandbox.stub(viewer, 'whenMessagingReady').returns(Promise.resolve()); sandbox.stub(viewer, 'getParam').withArgs('csi').returns('1'); sandbox.stub(viewer, 'isEmbedded').returns(true); installPerformanceService(win); perf = performanceFor(win); }); it('legacy-cdn-domain experiment enabled', () => { sandbox.stub(perf, 'getHostname_', () => 'cdn.ampproject.org'); return perf.coreServicesAvailable().then(() => { perf.flush(); expect(viewerSendMessageStub).to.be.calledWith('sendCsi', { ampexp: getMode(win).rtvVersion + ',legacy-cdn-domain', }); }); }); it('no experiment', () => { sandbox.stub(perf, 'getHostname_', () => 'curls.cdn.ampproject.org'); return perf.coreServicesAvailable().then(() => { perf.flush(); expect(viewerSendMessageStub).to.be.calledWith('sendCsi', { ampexp: getMode(win).rtvVersion, }); }); }); });
apache-2.0
translation-cards/txc-maker
src/main/java/org/mercycorps/translationcards/txcmaker/task/TxcPortingUtility.java
1451
package org.mercycorps.translationcards.txcmaker.task; import com.google.gson.Gson; import org.mercycorps.translationcards.txcmaker.model.Card; import org.mercycorps.translationcards.txcmaker.model.Deck; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; public class TxcPortingUtility { private static final Pattern FILE_URL_MATCHER = Pattern.compile( "https?://docs.google.com/spreadsheets/d/(.*?)(/.*)?$"); private static final Pattern DIR_URL_MATCHER = Pattern.compile( "https?://drive.google.com/corp/drive/folders/(.*)$"); public static String buildTxcJson(Deck exportSpec) { Gson gson = new Gson(); return gson.toJson(exportSpec); } public static String getSpreadsheetId(HttpServletRequest req) { String spreadsheetFileId = req.getParameter("docId"); Matcher spreadsheetFileIdMatcher = FILE_URL_MATCHER.matcher(spreadsheetFileId); if (spreadsheetFileIdMatcher.matches()) { spreadsheetFileId = spreadsheetFileIdMatcher.group(1); } return spreadsheetFileId; } public static String getAudioDirId(HttpServletRequest req) { String audioDirId = req.getParameter("audioDirId"); Matcher audioDirIdMatcher = DIR_URL_MATCHER.matcher(audioDirId); if (audioDirIdMatcher.matches()) { audioDirId = audioDirIdMatcher.group(1); } return audioDirId; } }
apache-2.0
JA-VON/Henderson-Painter-Language-HPL
src/hpl/sys/TestPrimitives.java
2255
package hpl.sys; import hpl.values.Painter; import hpl.values.PrimitivePainter; import java.awt.*; import java.awt.geom.Point2D; import javax.swing.*; public class TestPrimitives { static Screen screen; // display area static PainterFrame topLevelFrame; // top level topLevelFrame static Painter result; // painter to be drawn public static void main(String[] args) { JFrame display = new JFrame("Painter Tester"); //display.setSize(400, 400); display.getContentPane().setLayout(new GridLayout(1,1)); display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); topLevelFrame = new PainterFrame(1, 1); System.out.println("Created Frame..."); screen = new Screen(topLevelFrame, 400); System.out.println("Created Screen..."); display.getContentPane().add(screen); display.setSize(screen.getPreferredSize()); display.setVisible(true); try { Painter p = new PrimitivePainter("../images/uwicrest.jpg"); System.out.println("Created Image..."); PainterFrame f; // cycle through a number of demo combinations while (true) { for (float t = 0.0F; t < 1.0F; t = t + 0.1F) { Point2D origin = new Point2D.Float(t, 0F); Vector2D u = new Vector2D(1- t, t); Vector2D v = new Vector2D(-t, 1-t); f = new PainterFrame(origin, u, v); showPainter(p, f); screen.clear(); } // showPainter(CompoundPainter.rotate90(p, 1)); // showPainter(CompoundPainter.rotate90(p, 2)); // showPainter(CompoundPainter.rotate90(p, 3)); // showPainter(CompoundPainter.rotate(p, 30)); // showPainter(CompoundPainter.rotate(p, 60)); // showPainter(CompoundPainter.beside(p, p, .5)); // showPainter(CompoundPainter.above(p, p, .5)); // // CompoundPainter t1 = CompoundPainter.beside(p, p, .5); // showPainter(CompoundPainter.above(t1, t1, .5)); } } catch (HPLException hple){ System.out.println("Error:" + hple.getMessage()); } // end of try-catch } private static void showPainter(Painter result, PainterFrame f) { try { Thread.sleep(1500); result.render(screen, f); } catch(InterruptedException ie) { } } }
apache-2.0
agniruddra/TheStringsProject
App/TheStringsProject_WP8.0App/TheStringsProject_WP8.0App/Profile.xaml.cs
5356
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using TheStringsProject_WP8._0App.Models; using System.Windows.Media.Imaging; using System.IO.IsolatedStorage; using System.IO; using Microsoft.Phone.Tasks; using System.Globalization; namespace TheStringsProject_WP8._0App { public partial class Profile : PhoneApplicationPage { List<String> _Departments = new List<string>(); int index; public Profile() { InitializeComponent(); var name = App.AppSettings["Name"]; //Unit Test Data var college = "B.P. Poddar Institute of Management & Technology"; var department = "Computer Science Engineering"; DateTime birthday = (DateTime)App.AppSettings["dob"]; var email = "abhishekde@hotmail.com"; var contact = "8981169454"; DateTime lastlogin; if(App.AppSettings.Contains("login")){ lastlogin = Convert.ToDateTime(App.AppSettings["login"]); } else{ lastlogin = DateTime.Now; }//filldepartments(department); //Unit Test Data Ends DataContext = new User { Name = name.ToString(), College=college.ToString(), Department=department.ToString(), Dob=birthday, Email=email.ToString(), Contact=8981169454, LastLogin=lastlogin.ToString("dd/MMM/yyyy hh:mm:ss tt") }; } /*private void filldepartments(string department) { Departments d = new Departments(); _Departments = d.getDepartmentNames(); foreach (string _department in _Departments) { if (_department == department.ToString()) { index = _Departments.IndexOf(_department); } Department_Picker.Items.Add(_department); } Department_Picker.SelectedIndex = index; }*/ protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (App.AppSettings.Contains("photo")) { try { getPhoto(); } catch (Exception ex) { } } } private void getPhoto() { BitmapImage bi = new BitmapImage(); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read)) { bi.SetSource(fileStream); //this.Profile_Image.Height = bi.PixelHeight; //this.Profile_Image.Width = bi.PixelWidth; } } this.Profile_Image.Source = bi; this.Profile_Image.Stretch = System.Windows.Media.Stretch.Fill; } string tempJPEG = "image.jpg"; private void photoChooserTask_Completed(object sender, PhotoResult e) { using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (myIsolatedStorage.FileExists(tempJPEG)) { myIsolatedStorage.DeleteFile(tempJPEG); } IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(e.ChosenPhoto); WriteableBitmap wb = new WriteableBitmap(bitmap); // Encode WriteableBitmap object to a JPEG stream. Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); //wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); fileStream.Close(); } if (App.AppSettings.Contains("photo")) { App.AppSettings.Remove("photo"); App.AppSettings.Add("photo", "yes"); } else { App.AppSettings.Add("photo", "yes"); } } private void Profile_Image_Tap(object sender, System.Windows.Input.GestureEventArgs e) { PhotoChooserTask photoChooserTask = new PhotoChooserTask(); photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed); photoChooserTask.Show(); } private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e) { this.NavigationService.Navigate(new Uri("/Dashboard.xaml", UriKind.Relative)); } private void ApplicationBarIconButton_Click(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Dashboard.xaml", UriKind.Relative)); } } }
apache-2.0
Diullei/NetSpec
src/NetSpec/NetSpec.TestProject/SpecificationTest/DadoUmaEspecificacaoComTextoLivre.cs
3091
namespace NetSpec.TestProject.SpecificationTest { using System; using System.IO; using Core; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// Este teste tem por objetivo testar a execução de uma /// especificação simples escrita com texto livre. /// </summary> [TestClass] public class DadoUmaEspecificaçãoComTextoLivre { #region " Quando... " [TestInitialize] public void Quando() { Crio_UmObjetoSpecificationPassando_(UmaEspecificação); } #endregion #region " Deve... " [TestMethod] public void Deve_CriarUmObjetoSpecificationNãoNulo() { // Assert Assert.IsNotNull(_umObjetoSpecification); } [TestMethod] public void Deve_CriarUmObjetoSpecificationCom4Linhas() { // Act - Assert Assert.AreEqual(5, _umObjetoSpecification.LineSpecCollection.Count); } [TestMethod] public void Deve_ExecutarAEspecificação() { // Act _umObjetoSpecification.TryExecute(this); } [TestMethod] public void Deve_RetornarUmRelatórioEmFormatoConsoleIndicandoQueTodosOsItensForamExecutadosComSucesso() { // Arrange var log = new StringWriter(); Console.SetOut(log); // Act _umObjetoSpecification.TryExecute(this); // Assert Assert.AreEqual(UmRelatórioParaEspecificaçãoExecutadaComSucesso, log.ToString()); } #endregion #region " Campos Privados " private Specification _umObjetoSpecification; private int _calculadora; private bool _flagParaFalharTodasAsTarefas; private const string UmaEspecificação = @" Para testar uma calculadora quando eu informo o valor 4 e o valor 3 deve me retornar o valor 7 "; private const string UmRelatórioParaEspecificaçãoExecutadaComSucesso = @" Para testar uma calculadora quando eu informo o valor 4 e o valor 3 --> #Passed deve me retornar o valor 7 ---------------> #Passed "; #endregion #region " Métodos de Contextualização " public void Crio_UmObjetoSpecificationPassando_(string especificação) { _flagParaFalharTodasAsTarefas = false; _umObjetoSpecification = SpecificationBuilder.Builder(especificação); } #endregion #region " Métodos Auxiliares " public void QuandoEuInformoOValor_EOValor_(int primeiroValor, int segundoValor) { if(_flagParaFalharTodasAsTarefas) throw new Exception(); _calculadora = primeiroValor + segundoValor; } public void DeveMeRetornarOValor_(int resultado) { if (_flagParaFalharTodasAsTarefas) throw new Exception(); Assert.AreEqual(resultado, _calculadora); } #endregion } }
apache-2.0
gbhu/studynotes-projects
ShiroStudy/src/main/java/com/yummy/common/utils/UtilPath.java
3272
package com.yummy.common.utils; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; /** * */ public class UtilPath { /** * 获取到classes目录 * @return path */ public static String getClassPath(){ String systemName = System.getProperty("os.name"); //判断当前环境,如果是Windows 要截取路径的第一个 '/' if(!StringUtils.isBlank(systemName) && systemName.indexOf("Windows") !=-1){ return UtilPath.class.getResource("/").getFile().toString().substring(1); }else{ return UtilPath.class.getResource("/").getFile().toString(); } } /** * 获取当前对象的路径 * @param object * @return path */ public static String getObjectPath(Object object){ return object.getClass().getResource(".").getFile().toString(); } /** * 获取到项目的路径 * @return path */ public static String getProjectPath(){ return System.getProperty("user.dir"); } /** * 获取 root目录 * @return path */ public static String getRootPath(){ return getWEB_INF().replace("WEB-INF/", ""); } /** * 获取输出HTML目录 * @return */ public static String getHTMLPath(){ return getFreePath() + "html/html/"; } /** * 获取输出FTL目录 * @return */ public static String getFTLPath(){ return getFreePath() + "html/ftl/"; } /** * 获取 web-inf目录 * @return path */ public static String getWEB_INF(){ return getClassPath().replace("classes/", ""); } /** * 获取模版文件夹路径 * @return path */ public static String getFreePath(){ return getWEB_INF() + "ftl/"; } /** * 获取一个目录下所有的文件 * @param path * @return */ public static File[] getFiles(String path){ File file = new File(path); File[] files = file.listFiles(); return files; } /** * 获取当前时间 + 中国时区 * @return */ public static String getDate(){ SimpleDateFormat sformart=new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); String result = sformart.format(new Date()); result = result.replace("_", "T"); result += "+08:00"; return result; } /** * 不带结尾的XmlSitemap头部 * @return */ public static String getXmlSitemap(){ StringBuffer sb = new StringBuffer() .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + nextLine()) .append("<?xml-stylesheet type=\"text/xsl\" href=\"sitemap.xsl\"?>"+ nextLine()) .append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"+ nextLine()); return sb.toString(); } /** * 文本换行 * @return */ public static String nextLine(){ String nextLine = System.getProperty("line.separator"); return nextLine; } /** * 获取domain * @param request * @return */ public static String getDomain(HttpServletRequest request) { return ((String) request.getSession().getAttribute("nowPath")).replaceAll("(www.)|(.com)|(.net)|(http://)", "").trim(); } /** * 获取images 路径 * @return */ public static String getImages(){ return getRootPath() + "images/" ; } }
apache-2.0
ngageoint/scale
scale/queue/migrations/0017_queue_docker_image.py
450
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-30 17:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('queue', '0016_auto_20180123_2037'), ] operations = [ migrations.AddField( model_name='queue', name='docker_image', field=models.TextField(default=''), ), ]
apache-2.0
aws/aws-sdk-java
aws-java-sdk-workspacesweb/src/main/java/com/amazonaws/services/workspacesweb/model/transform/GetBrowserSettingsResultJsonUnmarshaller.java
2898
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.workspacesweb.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.workspacesweb.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetBrowserSettingsResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetBrowserSettingsResultJsonUnmarshaller implements Unmarshaller<GetBrowserSettingsResult, JsonUnmarshallerContext> { public GetBrowserSettingsResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetBrowserSettingsResult getBrowserSettingsResult = new GetBrowserSettingsResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return getBrowserSettingsResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("browserSettings", targetDepth)) { context.nextToken(); getBrowserSettingsResult.setBrowserSettings(BrowserSettingsJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return getBrowserSettingsResult; } private static GetBrowserSettingsResultJsonUnmarshaller instance; public static GetBrowserSettingsResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetBrowserSettingsResultJsonUnmarshaller(); return instance; } }
apache-2.0
muroc-lab/gyros
test/builder_test.cpp
3821
// author: Maciej Chałapuk // license: MIT // vim: ts=2 sw=2 expandtab #include "gyros/builder.hpp" #include "test/gyros/components.hpp" using Simple = test::gyros::component::EmptyComponent; using Counting = test::gyros::component::CountingComponent; using Complex = test::gyros::component::OneMemberComponent<int>; using Mock = test::gyros::component::MockComponent; template <class ...Types> using TypeList = gyros::util::type_list::TypeList<Types...>; namespace entity = gyros::entity; class gyros_Builder : public ::testing::Test { }; TEST_F(gyros_Builder, test_building_with_one_1c_entity) { auto scene = gyros::Builder<TypeList<Simple>>() .addEntity( entity::Builder<>() .emplace<Simple>()) .build(); } TEST_F(gyros_Builder, test_building_with_two_1c_entities_of_same_type) { auto scene = gyros::Builder<TypeList<Simple>>() .addEntity( entity::Builder<>() .emplace<Simple>()) .addEntity( entity::Builder<>() .emplace<Simple>()) .build(); } TEST_F(gyros_Builder, test_building_with_one_2c_entity) { auto scene = gyros::Builder<TypeList<Simple, Complex>>() .addEntity( entity::Builder<>() .emplace<Simple>() .emplace<Complex>()) .build(); } TEST_F(gyros_Builder, test_building_with_two_2c_entities_of_the_same_type) { auto scene = gyros::Builder<TypeList<Simple, Complex>>() .addEntity( entity::Builder<>() .emplace<Simple>() .emplace<Complex>()) .addEntity( entity::Builder<>() .emplace<Simple>() .emplace<Complex>()) .build(); } TEST_F(gyros_Builder, test_building_with_two_1c_entities_of_different_types) { auto scene = gyros::Builder<TypeList<Simple>, TypeList<Complex>>() .addEntity( entity::Builder<>() .emplace<Simple>()) .addEntity( entity::Builder<>() .emplace<Complex>()) .build(); } TEST_F(gyros_Builder, test_building_with_two_2c_ent_with_disjoint_c_types) { typedef gyros::Builder<TypeList<Simple, Counting>, TypeList<Complex, Mock>> TestedBuilder; auto scene = TestedBuilder() .addEntity( entity::Builder<>() .emplace<Simple>() .emplace<Counting>()) .addEntity( entity::Builder<>() .emplace<Complex>() .emplace<Mock>()) .build(); } TEST_F(gyros_Builder, test_building_with_two_2c_ent_with_1_c_type_intersect_same_pos) { typedef gyros::Builder<TypeList<Simple, Complex>, TypeList<Mock, Complex>> TestedBuilder; auto scene = TestedBuilder() .addEntity( entity::Builder<>() .emplace<Simple>() .emplace<Complex>()) .addEntity( entity::Builder<>() .emplace<Mock>() .emplace<Complex>()) .build(); } TEST_F(gyros_Builder, test_building_with_two_2c_ent_with_1_c_type_intersect_different_pos) { typedef gyros::Builder<TypeList<Simple, Complex>, TypeList<Complex, Mock>> TestedBuilder; auto scene = TestedBuilder() .addEntity( entity::Builder<>() .emplace<Simple>() .emplace<Complex>()) .addEntity( entity::Builder<>() .emplace<Complex>() .emplace<Mock>()) .build(); } TEST_F( gyros_Builder, test_building_with_two_2c_e_of_different_types_with_all_c_types_intersect ) { typedef gyros::Builder<TypeList<Simple, Complex>, TypeList<Complex, Simple>> TestedType; auto scene = TestedType() .addEntity( entity::Builder<>() .emplace<Simple>() .emplace<Complex>()) .addEntity( entity::Builder<>() .emplace<Complex>() .emplace<Simple>()) .build(); }
apache-2.0
rholt94/selenium-builder
seleniumbuilder/content/html/builder/selenium2/rcPlayback.js
61286
/** Playback system for remote webdriver. */ builder.selenium2.rcPlayback = {}; builder.selenium2.rcPlayback.getHostPort = function() { return bridge.prefManager.getCharPref("extensions.seleniumbuilder3.remote.hostport"); }; builder.selenium2.rcPlayback.setHostPort = function(hostPort) { bridge.prefManager.setCharPref("extensions.seleniumbuilder3.remote.hostport", hostPort); }; builder.selenium2.rcPlayback.getBrowserString = function() { return bridge.prefManager.getCharPref("extensions.seleniumbuilder3.remote.browserstring"); }; builder.selenium2.rcPlayback.setBrowserString = function(browserstring) { bridge.prefManager.setCharPref("extensions.seleniumbuilder3.remote.browserstring", browserstring); }; builder.selenium2.rcPlayback.getBrowserVersion = function() { return bridge.prefManager.getCharPref("extensions.seleniumbuilder3.remote.browserversion"); }; builder.selenium2.rcPlayback.setBrowserVersion = function(browserversion) { bridge.prefManager.setCharPref("extensions.seleniumbuilder3.remote.browserversion", browserversion); }; builder.selenium2.rcPlayback.getPlatform = function() { return bridge.prefManager.getCharPref("extensions.seleniumbuilder3.remote.platform"); }; builder.selenium2.rcPlayback.setPlatform = function(platform) { bridge.prefManager.setCharPref("extensions.seleniumbuilder3.remote.platform", platform); }; /** What interval to check waits for. */ builder.selenium2.rcPlayback.waitIntervalAmount = 100; /** waitMs / waitCycleDivisor -> max wait cycles. */ builder.selenium2.rcPlayback.waitCycleDivisor = 500; builder.selenium2.rcPlayback.runs = []; builder.selenium2.rcPlayback.makeRun = function(settings, script, postRunCallback, jobStartedCallback, stepStateCallback, initialVars, pausedCallback, preserveRunSession) { var ivs = {}; if (initialVars) { for (var k in initialVars) { ivs[k] = initialVars[k]; } } return { hostPort: settings.hostPort, browserstring: settings.browserstring, sessionID: null, currentStepIndex: -1, currentStep: null, script: script, stopped: false, playResult: { success: false }, pausedOnBreakpoint: false, vars: ivs, /** How many wait cycles have been run. */ waitCycle: 0, /** The wait timeout. */ waitTimeout: null, /** The wait timeout function. Not using interval to prevent overlapping */ waitFunction: null, /** The pause incrementor. */ pauseCounter: 0, /** The pause interval. */ pauseInterval: null, /** How many ms to wait for, implicitly or explicitly. */ waitMs: script.timeoutSeconds * 1000, postRunCallback: postRunCallback || null, jobStartedCallback: jobStartedCallback || null, stepStateCallback: stepStateCallback || function() {}, pausedCallback: pausedCallback || function() {}, /** Whether to preserve the playback session at the end of the run rather than shutting it down. */ preserveRunSession: preserveRunSession }; }; builder.selenium2.rcPlayback.getVars = function(r, callback) { callback(r.vars); }; builder.selenium2.rcPlayback.setVar = function(r, k, v, callback) { if (v == null) { delete r.vars[k]; } else { r.vars[k] = v; } if (callback) { callback(); } }; builder.selenium2.rcPlayback.isRunning = function() { return builder.selenium2.rcPlayback.runs.length > 0; }; builder.selenium2.rcPlayback.runReusing = function(r, postRunCallback, jobStartedCallback, stepStateCallback, initialVars, pausedCallback, preserveRunSession) { var settings = {hostPort:r.hostPort, browserstring:r.browserstring}; var r2 = builder.selenium2.rcPlayback.makeRun(settings, builder.getScript(), postRunCallback, jobStartedCallback, stepStateCallback, initialVars, pausedCallback, preserveRunSession); r2.vars = {}; for (var k in r.vars) { r2.vars[k] = r.vars[k]; } if (initialVars) { for (var k in initialVars) { r2.vars[k] = initialVars[k]; } } r2.sessionID = r.sessionID; builder.selenium2.rcPlayback.runs.push(r2); r2.jobStartedCallback(); r2.playResult.success = true; builder.selenium2.rcPlayback.playNextStep(r2); return r2; }; /** * @param settings {hostPort:string, browserstring:string, browserversion:string, platform:string} * @param postRunCallback function({success:bool, errorMessage:string|null}) * @param jobStartedCallback function(serverResponse:string) * @param stepStateCallback function(run:obj, script:Script, step:Step, stepIndex:int, state:builder.stepdisplay.state.*, message:string|null, error:string|null, percentProgress:int) */ builder.selenium2.rcPlayback.run = function(settings, postRunCallback, jobStartedCallback, stepStateCallback, initialVars, pausedCallback, preserveRunSession) { var r = builder.selenium2.rcPlayback.makeRun(settings, builder.getScript(), postRunCallback, jobStartedCallback, stepStateCallback, initialVars, pausedCallback, preserveRunSession); var hostPort = settings.hostPort; var browserstring = settings.browserstring; var browserversion = settings.browserversion; var platform = settings.platform; var name = _t('sel2_untitled_run'); if (r.script.path) { var name = r.script.path.path.split("/"); name = name[name.length - 1]; name = name.split(".")[0]; } name = "Selenium Builder " + browserstring + " " + (browserversion ? browserversion + " " : "") + (platform ? platform + " " : "") + name; builder.selenium2.rcPlayback.runs.push(r); var caps = { "name": name, "browserName":browserstring||"firefox", "version":browserversion||"", "platform":platform||"ANY" }; for (var key in settings) { if (!{hostPort:1, browserstring:1, browserversion: 1, platform: 1}[key]) { caps[key] = settings[key]; } } builder.selenium2.rcPlayback.send( r, "POST", "", JSON.stringify({"desiredCapabilities":caps}), builder.selenium2.rcPlayback.startJob, null, /* timeout */ 10000); return r; }; /** * Selenium server appends a series of null characters to its JSON responses - here we cut 'em off. */ builder.selenium2.rcPlayback.fixServerResponse = function(t) { var i = 0; for (; i < t.length; i++) { if (t.charCodeAt(i) == 0) { break; } } return t.substring(0, i); }; builder.selenium2.rcPlayback.parseServerResponse = function(t) { t = builder.selenium2.rcPlayback.fixServerResponse(t); if (t.length == 0) { return {}; } else { // The response may be some JSON, or it may also be a HTML page. try { return JSON.parse(t); } catch (e) { return {'value': {'message': t}}; } } }; builder.selenium2.rcPlayback.startJob = function(r, response) { if (r.jobStartedCallback) { r.jobStartedCallback(response); } r.sessionID = response.sessionId; r.playResult.success = true; builder.selenium2.rcPlayback.send(r, "POST", "/timeouts/implicit_wait", JSON.stringify({'ms':r.waitMs}), function(r, response) { builder.selenium2.rcPlayback.playNextStep(r); }); }; builder.selenium2.rcPlayback.continueTests = function() { for (var i = 0; i < builder.selenium2.rcPlayback.runs.length; i++) { var r = builder.selenium2.rcPlayback.runs[i]; if (r.pausedOnBreakpoint) { builder.selenium2.rcPlayback.continueRun(r); } } }; builder.selenium2.rcPlayback.continueRun = function(r) { r.pausedOnBreakpoint = false; r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.RUNNING, null, null); try { builder.selenium2.rcPlayback.types[r.currentStep.type.getName()](r, r.currentStep); } catch (e) { builder.selenium2.rcPlayback.recordError(r, e); } }; builder.selenium2.rcPlayback.playNextStep = function(r) { r.currentStepIndex++; if (r.currentStepIndex < r.script.steps.length) { r.currentStep = r.script.steps[r.currentStepIndex]; if (builder.breakpointsEnabled && r.currentStep.breakpoint) { r.pausedOnBreakpoint = true; r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.BREAKPOINT, null, null); r.pausedCallback(); return; } r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.RUNNING, null, null); try { builder.selenium2.rcPlayback.types[r.currentStep.type.getName()](r, r.currentStep); } catch (e) { builder.selenium2.rcPlayback.recordError(r, e); } } else { builder.selenium2.rcPlayback.shutdown(r); } }; builder.selenium2.rcPlayback.shutdown = function(r) { jQuery('#edit-rc-connecting').hide(); r.stopped = true; if (!r.preserveRunSession) { builder.selenium2.rcPlayback.send(r, "DELETE", "", ""); } builder.selenium2.rcPlayback.postShutdown(r); }; builder.selenium2.rcPlayback.postShutdown = function(r) { builder.selenium2.rcPlayback.runs = builder.selenium2.rcPlayback.runs.filter(function(r2) { return r2 != r; }); if (r.postRunCallback) { r.postRunCallback(r.playResult); } }; builder.selenium2.rcPlayback.getTestRuns = function() { return builder.selenium2.rcPlayback.runs; }; builder.selenium2.rcPlayback.stopTest = function(r) { if (!r.stopped) { builder.selenium2.rcPlayback.shutdown(r); } }; builder.selenium2.rcPlayback.hasError = function(response) { return !!response.status; // So undefined and 0 are fine. }; builder.selenium2.rcPlayback.handleError = function(r, response, errorThrown) { var err = _t('sel2_server_error'); if (errorThrown) { err += ": " + errorThrown; } if (response.value && response.value.message) { err += ": " + response.value.message.substring(0, 256); } builder.selenium2.rcPlayback.recordError(r, err); }; builder.selenium2.rcPlayback.recordError = function(r, err) { if (r.currentStepIndex === -1) { // If we can't connect to the server right at the start, just attach the error message to the // first step. r.currentStepIndex = 0; } else { if (r.currentStep.negated && r.currentStep.type.getName().startsWith("assert")) { // Record this as a failed result instead - this way it will be turned into a successful result // by recordResult. builder.selenium2.rcPlayback.recordResult(r, {success: false}); return; } } r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.ERROR, null, err); r.playResult.success = false; r.playResult.errormessage = err; builder.selenium2.rcPlayback.shutdown(r); }; builder.selenium2.rcPlayback.send = function(r, http_method, path, msg, callback, errorCallback, timeout) { timeout = timeout || 300000; var url = null; if (r.sessionID) { url = "http://" + r.hostPort + "/wd/hub/session/" + r.sessionID + path; } else { url = "http://" + r.hostPort + "/wd/hub/session"; } jQuery.ajax({ // Because the server appends null characters to its output, we want to disable automatic // JSON parsing in jQuery. dataType: "html", // But because the server crashes if we don't accept application/json, we explicitly set it to. headers: { "Accept" : "application/json, image/png", "Content-Type": "text/plain; charset=utf-8" }, type: http_method || "POST", url: url, data: msg, timeout: timeout, success: function(t) { if (r.stopped) { return; } // We've broken up with the server and are letting the calls go to voicemail. if (callback) { try { callback(r, builder.selenium2.rcPlayback.parseServerResponse(t)); } catch (err) { builder.selenium2.rcPlayback.recordError(r, err); } } else { builder.selenium2.rcPlayback.recordResult(r, {'success': true}); } }, error: function(xhr, textStatus, errorThrown) { if (r.stopped) { return; } // We've broken up with the server and are letting the calls go to voicemail. var response = ""; if (textStatus == 'timeout') { response = 'timeout'; } else { response = builder.selenium2.rcPlayback.parseServerResponse(xhr.responseText); } if (errorCallback) { try { errorCallback(r, response); } catch (err) { builder.selenium2.rcPlayback.recordError(r, err); } } else { builder.selenium2.rcPlayback.handleError(r, response, errorThrown); } } }); }; /** Performs ${variable} substitution for parameters. */ builder.selenium2.rcPlayback.param = function(r, pName) { var output = ""; var hasDollar = false; var insideVar = false; var varName = ""; var text = r.currentStep.type.getParamType(pName) == "locator" ? r.currentStep[pName].getValue() : r.currentStep[pName]; for (var i = 0; i < text.length; i++) { var ch = text.substring(i, i + 1); if (insideVar) { if (ch == "}") { if (r.vars[varName] == undefined) { throw "Variable not set: " + varName + "."; } output += r.vars[varName]; insideVar = false; hasDollar = false; varName = ""; } else { varName += ch; } } else { // !insideVar if (hasDollar) { if (ch == "{") { insideVar = true; } else { hasDollar = false; output += "$" + ch; } } else { if (ch == "$") { hasDollar = true; } else { output += ch; } } } } return r.currentStep.type.getParamType(pName) == "locator" ? {"using": r.currentStep[pName].getName(builder.selenium2), "value": output} : output; }; builder.selenium2.rcPlayback.print = function(r, text) { r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, text, null); }; builder.selenium2.rcPlayback.recordResult = function(r, result) { if (r.currentStep.negated) { result.message = r.currentStep.type.getName() + " " + _t('sel2_is') + " " + result.success; result.success = !result.success; } if (result.success) { r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.SUCCEEDED, null, null); } else { r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.FAILED, null, null); r.playResult.success = false; if (result.message) { r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, result.message, null); r.playResult.errormessage = result.message; } } builder.selenium2.rcPlayback.playNextStep(r); }; builder.selenium2.rcPlayback.findElement = function(r, locator, callback, errorCallback) { builder.selenium2.rcPlayback.send(r, "POST", "/element", JSON.stringify(locator), function(r, response) { if (builder.selenium2.rcPlayback.hasError(r, response)) { if (errorCallback) { try { errorCallback(r, response); } catch (e) { builder.selenium2.rcPlayback.recordError(r, e); } } else { builder.selenium2.rcPlayback.handleError(r, response); } } else { if (callback) { try { callback(r, response.value.ELEMENT); } catch (e) { builder.selenium2.rcPlayback.recordError(r, e); } } else { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } } } ); }; builder.selenium2.rcPlayback.findElements = function(r, locator, callback, errorCallback) { builder.selenium2.rcPlayback.send(r, "POST", "/elements", JSON.stringify(locator), function(r, response) { if (builder.selenium2.rcPlayback.hasError(r, response)) { if (errorCallback) { try { errorCallback(r, response); } catch (e) { builder.selenium2.rcPlayback.recordError(r, e); } } else { builder.selenium2.rcPlayback.handleError(r, response); } } else { if (callback) { var elids = []; for (var i = 0; i < response.value.length; i++) { elids.push(response.value[i].ELEMENT); } callback(r, elids); } else { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } } } ); }; /** Repeatedly calls testFunction, allowing it to tell us if it was successful. */ builder.selenium2.rcPlayback.wait = function(r, testFunction) { r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, null, null, 1); r.waitCycle = 0; // Using a timeout that keeps on re-installing itself rather than an interval to prevent // the case where the request takes longer than the timeout and requests overlap. r.waitFunction = function() { try { testFunction(r, function(r, success) { if (success != r.currentStep.negated) { r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, null, null, 0); builder.selenium2.rcPlayback.recordResult(r, {'success': success}); return; } if (r.waitCycle++ > r.waitMs / builder.selenium2.rcPlayback.waitCycleDivisor) { r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, null, null, 0); builder.selenium2.rcPlayback.recordError(r, "Wait timed out."); return; } r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, null, null, 1 + r.waitCycle * 99 * builder.selenium2.rcPlayback.waitCycleDivisor / r.waitMs); r.waitTimeout = window.setTimeout( r.waitFunction, builder.selenium2.rcPlayback.waitIntervalAmount ); }); } catch (e) { builder.selenium2.rcPlayback.recordError(r, e); } }; r.waitTimeout = window.setTimeout(r.waitFunction, 1); }; builder.selenium2.rcPlayback.types = {}; builder.selenium2.rcPlayback.types.pause = function(r, step) { r.pauseCounter = 0; var max = builder.selenium2.rcPlayback.param(r, "waitTime") / 100; r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, null, null, 1); r.pauseInterval = setInterval(function() { if (r.stopped) { window.clearInterval(r.pauseInterval); return; } r.pauseCounter++; r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, null, null, 1 + 99 * r.pauseCounter / max); if (r.pauseCounter >= max) { window.clearInterval(r.pauseInterval); r.stepStateCallback(r, r.script, r.currentStep, r.currentStepIndex, builder.stepdisplay.state.NO_CHANGE, null, null, 0); builder.selenium2.rcPlayback.recordResult(r, {success: true}); } }, 100); }; builder.selenium2.rcPlayback.types.print = function(r, step) { builder.selenium2.rcPlayback.print(r, builder.selenium2.rcPlayback.param(r, "text")); builder.selenium2.rcPlayback.recordResult(r, {success: true}); }; builder.selenium2.rcPlayback.types.store = function(r, step) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = builder.selenium2.rcPlayback.param(r, "text"); builder.selenium2.rcPlayback.recordResult(r, {success: true}); }; builder.selenium2.rcPlayback.types.get = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/url", JSON.stringify({'url': builder.selenium2.rcPlayback.param(r, "url")})); }; builder.selenium2.rcPlayback.types.goBack = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/back", ""); }; builder.selenium2.rcPlayback.types.goForward = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/forward", ""); }; builder.selenium2.rcPlayback.types.refresh = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/refresh", ""); }; builder.selenium2.rcPlayback.types.setWindowSize = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/window_handle", "", function(r, handle) { builder.selenium2.rcPlayback.send(r, "POST", "/window/" + handle + "/size", JSON.stringify({"width": parseInt(builder.selenium2.rcPlayback.param(r, "width")), "height": parseInt(builder.selenium2.rcPlayback.param(r, "height"))})); }); }; builder.selenium2.rcPlayback.types.clickElement = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/click", ""); }); }; builder.selenium2.rcPlayback.types.doubleClickElement = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/click", "", function(r, response) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/click", ""); }); }); }; builder.selenium2.rcPlayback.types.mouseOverElement = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "POST", "/moveto", JSON.stringify({ 'element': id })); }); }; builder.selenium2.rcPlayback.types.submitElement = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/submit", ""); }); }; builder.selenium2.rcPlayback.types.setElementText = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/click", "", function(r, response) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/clear", "", function(r, response) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/value", JSON.stringify({ 'value': [builder.selenium2.rcPlayback.param(r, "text")] })); }); }); }); }; builder.selenium2.rcPlayback.types.sendKeysToElement = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/click", "", function(r, response) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/value", JSON.stringify({ 'value': [builder.selenium2.rcPlayback.param(r, "text")] })); }); }); }; builder.selenium2.rcPlayback.types.setElementSelected = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/selected", "", function(r, response) { if (response.value) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/click", ""); } }); }); }; builder.selenium2.rcPlayback.types.setElementNotSelected = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/selected", "", function(r, response) { if (!response.value) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/click", ""); } }); }); }; builder.selenium2.rcPlayback.types.clearSelections = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + id + "/elements", JSON.stringify({'using': 'tag name', 'value': 'option'}), function(r, response) { var ids = response.value; function deselect(r, i) { if (i >= ids.length) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + ids[i].ELEMENT + "/selected", "", function(r, response) { if (response.value) { builder.selenium2.rcPlayback.send(r, "POST", "/element/" + ids[i].ELEMENT + "/click", "", function(r, response) { deselect(r, i + 1); }); } else { deselect(r, i + 1); } }); } } deselect(r, 0); }); }); }; builder.selenium2.rcPlayback.types.verifyTextPresent = function(r, step) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { if (response.value.indexOf(builder.selenium2.rcPlayback.param(r, "text")) != -1) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_text_not_present', builder.selenium2.rcPlayback.param(r, "text"))}); } }); }); }; builder.selenium2.rcPlayback.types.assertTextPresent = function(r, step) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { if (response.value.indexOf(builder.selenium2.rcPlayback.param(r, "text")) != -1) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_text_not_present', builder.selenium2.rcPlayback.param(r, "text"))); } }); }); }; builder.selenium2.rcPlayback.types.waitForTextPresent = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { callback(r, response.value.indexOf(builder.selenium2.rcPlayback.param(r, "text")) != -1); }, /*error*/ function(r) { callback(r, false); }); }, /*error*/ function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeTextPresent = function(r, step) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value.indexOf(builder.selenium2.rcPlayback.param(r, "text")) != -1; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.verifyBodyText = function(r, step) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "text")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_body_text_does_not_match', builder.selenium2.rcPlayback.param(r, "text"))}); } }); }); }; builder.selenium2.rcPlayback.types.assertBodyText = function(r, step) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "text")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_body_text_does_not_match', builder.selenium2.rcPlayback.param(r, "text"))); } }); }); }; builder.selenium2.rcPlayback.types.waitForBodyText = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "text")); }, /*error*/ function(r) { callback(r, false); }); }, /*error*/ function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeBodyText = function(r, step) { builder.selenium2.rcPlayback.findElement(r, {'using': 'tag name', 'value': 'body'}, function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.verifyElementPresent = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); }, function(r) { builder.selenium2.rcPlayback.recordResult(r, {success: false}); }); }; builder.selenium2.rcPlayback.types.assertElementPresent = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); }, function(r) { builder.selenium2.rcPlayback.recordError(r, _t('sel2_element_not_found')); }); }; builder.selenium2.rcPlayback.types.waitForElementPresent = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { callback(r, true); }, function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeElementPresent = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = true; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }, function(r) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = false; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.verifyPageSource = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/source", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "source")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_source_does_not_match')}); } }); }; builder.selenium2.rcPlayback.types.assertPageSource = function(r, step) { builder.selenium2.rcPlayback.send("GET", "/source", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "source")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_source_does_not_match')); } }); }; builder.selenium2.rcPlayback.types.waitForPageSource = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "GET", "/source", "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "source")); }); }); }; builder.selenium2.rcPlayback.types.storePageSource = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/source", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.verifyText = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "text")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_element_text_does_not_match', response.value, builder.selenium2.rcPlayback.param(r, "text"))}); } }); }); }; builder.selenium2.rcPlayback.types.assertText = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "text")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_element_text_does_not_match', response.value, builder.selenium2.rcPlayback.param(r, "text"))); } }); }); }; builder.selenium2.rcPlayback.types.waitForText = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "text")); }, /*error*/ function(r) { callback(r, false); }); }, /*error*/ function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeText = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/text", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.verifyCurrentUrl = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/url", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "url")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_url_does_not_match', response.value, builder.selenium2.rcPlayback.param("url"))}); } }); }; builder.selenium2.rcPlayback.types.assertCurrentUrl = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/url", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "url")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_url_does_not_match', response.value, builder.selenium2.rcPlayback.param("url"))); } }); }; builder.selenium2.rcPlayback.types.waitForCurrentUrl = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "GET", "/url", "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "url")); }); }); }; builder.selenium2.rcPlayback.types.storeCurrentUrl = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/url", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.verifyTitle = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/title", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "title")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_title_does_not_match', response.value, builder.selenium2.rcPlayback.param(r, "title"))}); } }); }; builder.selenium2.rcPlayback.types.assertTitle = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/title", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "title")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_title_does_not_match', response.value, builder.selenium2.rcPlayback.param("title"))); } }); }; builder.selenium2.rcPlayback.types.waitForTitle = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "GET", "/title", "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "title")); }); }); }; builder.selenium2.rcPlayback.types.storeTitle = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/title", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.verifyElementSelected = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/selected", "", function(r, response) { if (response.value) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_element_not_selected')}); } }); }); }; builder.selenium2.rcPlayback.types.assertElementSelected = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/selected", "", function(r, response) { if (response.value) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_element_not_selected')); } }); }); }; builder.selenium2.rcPlayback.types.waitForElementSelected = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/selected", "", function(r, response) { callback(r, response.value); }, /*error*/ function(r) { callback(r, false); }); }, /*error*/ function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeElementSelected = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/selected", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.verifyElementValue = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/value", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_element_value_doesnt_match', response.value, builder.selenium2.rcPlayback.param(r, "value"))}); } }); }); }; builder.selenium2.rcPlayback.types.assertElementValue = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/value", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_element_value_doesnt_match', response.value, builder.selenium2.rcPlayback.param(r, "value"))); } }); }); }; builder.selenium2.rcPlayback.types.waitForElementValue = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/value", "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "value")); }, /*error*/ function(r) { callback(r, false); }); }, /*error*/ function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeElementValue = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/value", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.verifyElementAttribute = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/" + builder.selenium2.rcPlayback.param(r, "attributeName"), "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_attribute_value_doesnt_match', builder.selenium2.rcPlayback.param(r, "attributeName"), response.value, builder.selenium2.rcPlayback.param(r, "value"))}); } }); }); }; builder.selenium2.rcPlayback.types.assertElementAttribute = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/" + builder.selenium2.rcPlayback.param(r, "attributeName"), "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_attribute_value_doesnt_match', builder.selenium2.rcPlayback.param(r, "attributeName"), response.value, builder.selenium2.rcPlayback.param(r, "value"))); } }); }); }; builder.selenium2.rcPlayback.types.waitForElementAttribute = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/" + builder.selenium2.rcPlayback.param(r, "attributeName"), "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "value")); }, /*error*/ function(r) { callback(r, false); }); }, /*error*/ function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeElementAttribute = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/attribute/" + builder.selenium2.rcPlayback.param(r, "attributeName"), "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.verifyElementStyle = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/css/" + builder.selenium2.rcPlayback.param(r, "propertyName"), "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_css_value_doesnt_match', builder.selenium2.rcPlayback.param(r, "propertyName"), response.value, builder.selenium2.rcPlayback.param(r, "value"))}); } }); }); }; builder.selenium2.rcPlayback.types.assertElementStyle = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/css/" + builder.selenium2.rcPlayback.param(r, "propertyName"), "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_css_value_doesnt_match', builder.selenium2.rcPlayback.param(r, "propertyName"), response.value, builder.selenium2.rcPlayback.param(r, "value"))); } }); }); }; builder.selenium2.rcPlayback.types.waitForElementStyle = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/css/" + builder.selenium2.rcPlayback.param(r, "propertyName"), "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "value")); }, /*error*/ function(r) { callback(r, false); }); }, /*error*/ function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeElementStyle = function(r, step) { builder.selenium2.rcPlayback.findElement(r, builder.selenium2.rcPlayback.param(r, "locator"), function(r, id) { builder.selenium2.rcPlayback.send(r, "GET", "/element/" + id + "/css/" + builder.selenium2.rcPlayback.param(r, "propertyName"), "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.deleteCookie = function(r, step) { builder.selenium2.rcPlayback.send(r, "DELETE", "/cookie/" + builder.selenium2.rcPlayback.param(r, "name"), ""); }; builder.selenium2.rcPlayback.types.addCookie = function(r, step) { var cookie = { 'name': builder.selenium2.rcPlayback.param(r, "name"), 'value': builder.selenium2.rcPlayback.param(r, "value"), 'secure': false, 'path': '/', 'class': 'org.openqa.selenium.Cookie' }; var opts = builder.selenium2.rcPlayback.param(r, "options").split(","); for (var i = 0; i < opts.length; i++) { var kv = opts[i].trim().split("="); if (kv.length == 1) { continue; } if (kv[0] == "path") { cookie.path = kv[1]; } if (kv[0] == "max_age") { cookie.expiry = (new Date().getTime()) / 1000 + parseInt(kv[1]); } } builder.selenium2.rcPlayback.send(r, "POST", "/cookie", JSON.stringify({'cookie': cookie})); }; builder.selenium2.rcPlayback.types.verifyCookieByName = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { if (response.value[i].value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_cookie_value_doesnt_match', builder.selenium2.rcPlayback.param(r, "name"), response.value[i].value, builder.selenium2.rcPlayback.param(r, "value"))}); } return; } } builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_no_cookie_found', builder.selenium2.rcPlayback.param(r, "name"))}); }); }; builder.selenium2.rcPlayback.types.assertCookieByName = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { if (response.value[i].value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_cookie_value_doesnt_match', builder.selenium2.rcPlayback.param(r, "name"), response.value[i].value, builder.selenium2.rcPlayback.param(r, "value"))); } return; } } builder.selenium2.rcPlayback.recordError(r, _t('sel2_no_cookie_found', builder.selenium2.rcPlayback.param(r, "name"))); }); }; builder.selenium2.rcPlayback.types.waitForCookieByName = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { callback(r, response.value[i].value == builder.selenium2.rcPlayback.param(r, "value")); return; } } callback(r, false); }, function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeCookieByName = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value[i].value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); return; } } builder.selenium2.rcPlayback.recordError(r, _t('sel2_no_cookie_found', builder.selenium2.rcPlayback.param(r, "name"))); }); }; builder.selenium2.rcPlayback.types.verifyCookiePresent = function(r, step) { builder.selenium2.rcPlayback.send("r, GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); return; } } builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_no_cookie_found', builder.selenium2.rcPlayback.param(r, "name"))}); }); }; builder.selenium2.rcPlayback.types.assertCookiePresent = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); return; } } builder.selenium2.rcPlayback.recordError(r, _t('sel2_no_cookie_found', builder.selenium2.rcPlayback.param(r, "name"))); }); }; builder.selenium2.rcPlayback.types.waitForCookiePresent = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { callback(r, true); return; } } callback(r, false); }, function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeCookiePresent = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/cookie", "", function(r, response) { for (var i = 0; i < response.value.length; i++) { if (response.value[i].name == builder.selenium2.rcPlayback.param(r, "name")) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = true; builder.selenium2.rcPlayback.recordResult(r, {success: true}); return; } } r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = false; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.saveScreenshot = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/screenshot", "", function(r, response) { bridge.writeBinaryFile(builder.selenium2.rcPlayback.param(r, "file"), bridge.decodeBase64(response.value)); builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.switchToFrame = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/frame", JSON.stringify({'id': builder.selenium2.rcPlayback.param(r, "identifier")})); }; builder.selenium2.rcPlayback.types.switchToFrameByIndex = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/frame", JSON.stringify({'id': parseInt(builder.selenium2.rcPlayback.param(r, "index"))})); }; builder.selenium2.rcPlayback.types.switchToWindow = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/window", JSON.stringify({'name': builder.selenium2.rcPlayback.param(r, "name")})); }; builder.selenium2.rcPlayback.types.switchToWindowByIndex = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/window", JSON.stringify({'id': parseInt(builder.selenium2.rcPlayback.param(r, "index"))})); }; builder.selenium2.rcPlayback.types.switchToDefaultContent = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/frame", JSON.stringify({'id': null})); }; builder.selenium2.rcPlayback.types.verifyAlertText = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "text")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_alert_text_does_not_match')}); } }); }; builder.selenium2.rcPlayback.types.assertAlertText = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "text")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_alert_text_does_not_match', response.value, builder.selenium2.rcPlayback.param(r, "text"))); } }); }; builder.selenium2.rcPlayback.types.waitForAlertText = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "text")); }); }); }; builder.selenium2.rcPlayback.types.storeAlertText = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.verifyAlertPresent = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); }, function(r) { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_no_alert_present')}); }); }; builder.selenium2.rcPlayback.types.assertAlertPresent = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.waitForAlertPresent = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { callback(r, true); }, function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeAlertPresent = function(r, step) { builder.selenium2.rcPlayback.send(r, "GET", "/alert_text", "", function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = true; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }, function(r) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = false; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.answerAlert = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/alert_text", JSON.stringify({'text': builder.selenium2.rcPlayback.param(r, "text")}), function(r, response) { builder.selenium2.rcPlayback.send(r, "POST", "/accept_alert", "", function(r, response) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }); }; builder.selenium2.rcPlayback.types.acceptAlert = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/accept_alert", "", function(r, response) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.dismissAlert = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/dismiss_alert", "", function(r, response) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; builder.selenium2.rcPlayback.types.verifyEval = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/execute", JSON.stringify({'script': builder.selenium2.rcPlayback.param(r, "script"), 'args': []}), function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordResult(r, {success: false, message: _t('sel2_eval_false', result.value, builder.selenium2.rcPlayback.param(r, "value"))}); } }); }; builder.selenium2.rcPlayback.types.assertEval = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/execute", JSON.stringify({'script': builder.selenium2.rcPlayback.param(r, "script"), 'args': []}), function(r, response) { if (response.value == builder.selenium2.rcPlayback.param(r, "value")) { builder.selenium2.rcPlayback.recordResult(r, {success: true}); } else { builder.selenium2.rcPlayback.recordError(r, _t('sel2_eval_false', response.value, builder.selenium2.rcPlayback.param(r, "value"))); } }); }; builder.selenium2.rcPlayback.types.waitForEval = function(r, step) { builder.selenium2.rcPlayback.wait(r, function(r, callback) { builder.selenium2.rcPlayback.send(r, "POST", "/execute", JSON.stringify({'script': builder.selenium2.rcPlayback.param(r, "script"), 'args': []}), function(r, response) { callback(r, response.value == builder.selenium2.rcPlayback.param(r, "value")); }, function(r) { callback(r, false); }); }); }; builder.selenium2.rcPlayback.types.storeEval = function(r, step) { builder.selenium2.rcPlayback.send(r, "POST", "/execute", JSON.stringify({'script': builder.selenium2.rcPlayback.param(r, "script"), 'args': []}), function(r, response) { r.vars[builder.selenium2.rcPlayback.param(r, "variable")] = response.value; builder.selenium2.rcPlayback.recordResult(r, {success: true}); }); }; if (builder && builder.loader && builder.loader.loadNextMainScript) { builder.loader.loadNextMainScript(); }
apache-2.0
ssilviogit/pml
model/_IterableCollection.class.php
1251
<?php /* * Copyright 2017 Silvio Sparapano <ssilvio@libero.it>. * * 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. */ namespace model; require_once($_SERVER["DOCUMENT_ROOT"] .DIRECTORY_SEPARATOR. "controller" .DIRECTORY_SEPARATOR. "errorHandler.php"); /** * Description of _IterableCollection * * @author Silvio Sparapano <ssilvio@libero.it> */ abstract class _IterableCollection implements \IteratorAggregate { private $items = array(); public function getIterator(){ return new \ArrayIterator($this->items); } protected function _setCollection(array $items){ $this->items = $items; } protected function _addItem($item){ array_push($this->items, $item); } }
apache-2.0
kef/hieos
src/xds/src/com/vangent/hieos/services/xds/registry/storedquery/GetFolders.java
3991
/* * This code is subject to the HIEOS License, Version 1.0 * * Copyright(c) 2008-2009 Vangent, Inc. All rights reserved. * * 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 com.vangent.hieos.services.xds.registry.storedquery; import com.vangent.hieos.services.xds.registry.backend.BackendRegistry; import org.apache.axiom.om.OMElement; import com.vangent.hieos.xutil.exception.MetadataValidationException; import com.vangent.hieos.xutil.exception.XdsException; import com.vangent.hieos.xutil.exception.XdsInternalException; import com.vangent.hieos.xutil.exception.XdsResultNotSinglePatientException; import com.vangent.hieos.xutil.metadata.structure.Metadata; import com.vangent.hieos.xutil.metadata.structure.MetadataParser; import com.vangent.hieos.xutil.metadata.structure.SqParams; import com.vangent.hieos.xutil.response.Response; import com.vangent.hieos.xutil.xlog.client.XLogMessage; import java.util.List; /** * * @author NIST (Adapted by Bernie Thuman). */ public class GetFolders extends StoredQuery { /** * */ public GetFolders(SqParams params, boolean returnLeafClass, Response response, XLogMessage logMessage, BackendRegistry backendRegistry) throws MetadataValidationException { super(params, returnLeafClass, response, logMessage, backendRegistry); // param name, required?, multiple?, is string?, is code?, support AND/OR, alternative validateQueryParam("$XDSFolderEntryUUID", true, true, true, false, false, "$XDSFolderUniqueId", "$XDSFolderLogicalID"); validateQueryParam("$XDSFolderUniqueId", true, true, true, false, false, "$XDSFolderEntryUUID", "$XDSFolderLogicalID"); validateQueryParam("$XDSFolderLogicalID", false, true, true, false, false, "$XDSFolderUniqueId", "$XDSFolderEntryUUID"); validateQueryParam("$MetadataLevel", false, false, false, false, false, (String[]) null); if (this.hasValidationErrors()) { throw new MetadataValidationException("Metadata Validation error present"); } } /** * * @return * @throws XdsException */ public Metadata runInternal() throws XdsException { Metadata metadata; SqParams params = this.getSqParams(); String metadataLevel = params.getIntParm("$MetadataLevel"); List<String> folderUUIDs = params.getListParm("$XDSFolderEntryUUID"); List<String> folderUIDs = params.getListParm("$XDSFolderUniqueId"); List<String> lids = params.getListParm("$XDSFolderLogicalID"); OMElement ele; if (folderUUIDs != null) { // starting from uuid ele = getFolderByUUID(folderUUIDs); } else if (folderUIDs != null) { // starting from uniqueid ele = getFolderByUID(folderUIDs); } else if (lids != null) { // starting from lid ele = getFolderByLID(lids); } else { throw new XdsInternalException("GetFolders Stored Query: UUID, UID or LID not specified in query"); } metadata = MetadataParser.parseNonSubmission(ele); return metadata; } /** * * @param validateConsistentPatientId * @param metadata * @throws XdsException * @throws XdsResultNotSinglePatientException */ @Override public void validateConsistentPatientId(boolean validateConsistentPatientId, Metadata metadata) throws XdsException, XdsResultNotSinglePatientException { // Default implementation. // Can't really do anything here, since metadata update is implemented. } }
apache-2.0
javalivepeng/tuibei
crawler/src/crawler/YanBao.java
12317
package crawler; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.tuibei.crawler.beans.YanBaoBean; import com.tuibei.crawler.po.YanBaoPo; public class YanBao { static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); static String longUrl="http://www.tuibei.com.cn/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1"; public static void main(String[] args) { List<YanBaoBean> beanList = new ArrayList<YanBaoBean>(50); String baseUrl = getBaseUrl(50,1); YanBaoPo yanBaoPo = getYanBo(baseUrl); for(int i=5;i>0;i--){ baseUrl = getBaseUrl(50,i); yanBaoPo = getYanBo(baseUrl); if(yanBaoPo == null) break; beanList.addAll(convert2List(yanBaoPo.getData())); Collections.reverse(beanList); System.out.println(beanList.size()); System.out.println("研报抓取完成……当前进度:第"+i+"页,共"+yanBaoPo.getPages()+"页"); faTie(beanList); beanList.clear(); try { Thread.sleep(new Random().nextInt(50000)); } catch (InterruptedException e) { e.printStackTrace(); } } } public static String getNewerDate(CloseableHttpClient httpclient) throws Exception{ HttpGet hashGet = getGetMethod("http://www.tuibei.com.cn/forum.php?mod=forumdisplay&fid=85"); CloseableHttpResponse hashResponse = httpclient.execute(hashGet); HttpEntity hashentity = hashResponse.getEntity(); if (hashentity != null) { String buffer = EntityUtils.toString(hashentity, "UTF-8"); Elements tieZiList = Jsoup.parse(buffer).getElementsByAttributeValue("class","comeing_bd"); for(Element tr: tieZiList ){ Elements ths = tr.getElementsByTag("th"); for(Element th : ths){ Elements as = th.getElementsByTag("a"); if(as.size()>=2){ Element a = as.get(1); if(a!=null && a.hasText()){ String title = as.get(1).html(); String date = title.substring(title.indexOf("【")+1,title.indexOf("【")+1+10); return date; } } } } } hashGet.releaseConnection(); return ""; } public static CloseableHttpClient login(){ CloseableHttpClient loginClient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(longUrl); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("fastloginfield", "username")); params.add(new BasicNameValuePair("username", "javalive")); params.add(new BasicNameValuePair("password", "411327")); params.add(new BasicNameValuePair("quickforward", "yes")); params.add(new BasicNameValuePair("handlekey", "ls")); httppost.setEntity(new UrlEncodedFormEntity(params,Consts.UTF_8)); CloseableHttpResponse response; try { response = loginClient.execute(httppost); if(response.getStatusLine().getStatusCode()==200) { System.out.println("login success!!"); getNewerDate(loginClient); return loginClient; } } catch (Exception e) { e.printStackTrace(); }finally{ httppost.releaseConnection(); } return null; } public static Map<String,String> constParaMap(){ HashMap<String, String> nv = new HashMap<String, String>(); nv.put("posttime", (System.currentTimeMillis()/1000)+""); nv.put("allownoticeauthor", "1"); nv.put("ordertype", "1"); nv.put("replycredit_extcredits", "0"); nv.put("replycredit_membertimes", "1"); nv.put("replycredit_random", "100"); nv.put("replycredit_times", "1"); nv.put("save", ""); nv.put("usesig", "1"); nv.put("wysiwyg", "1"); return nv; } public static void faTie(List<YanBaoBean> beanList){ try { CloseableHttpClient httpclient = login(); String lastDt = getNewerDate(httpclient); Date lastDate = sdf.parse(lastDt); int n = 0; if(httpclient != null && beanList.size()>0) { for(YanBaoBean bean : beanList){ if(sdf.parse(bean.getUptime()).getTime()<=lastDate.getTime()) continue; n++; HashMap<String, String> nv = new HashMap<String, String>(); nv.put("subject", bean.getYanbaoTitle()); nv.put("message",bean.getYanbaoContent()); nv.put("tags",bean.getTages()); nv.put("formhash",getHash(httpclient)); nv.putAll(constParaMap()); HttpPost tieziPost = getPostMethod("http://www.tuibei.com.cn/forum.php?mod=post&action=newthread&fid=85&extra=&topicsubmit=yes",nv); tieziPost.addHeader("Referer","http://www.tuibei.com.cn/forum.php?mod=post&action=newthread&fid=85"); int status = -10; while(!(status == 200 || status == 301)){ try { CloseableHttpResponse tieziResponse = httpclient.execute(tieziPost); HttpEntity entity = tieziResponse.getEntity(); if (entity != null) { String buffer = EntityUtils.toString(entity, "UTF-8"); System.out.println("页面:"+buffer.toString()); } status = tieziResponse.getStatusLine().getStatusCode(); tieziPost.releaseConnection(); System.out.println("发帖成功!!"); } catch (Exception e) { e.printStackTrace(); } } if(n%5==0){ httpclient.close(); Thread.sleep(2000); httpclient = login(); } System.out.println("帖子进度:"+n); } httpclient.close(); } } catch (Exception e) { e.printStackTrace(); } } public static String getHash(CloseableHttpClient httpclient) throws Exception{ HttpGet hashGet = getGetMethod("http://www.tuibei.com.cn/forum.php?mod=post&action=newthread&fid=85"); CloseableHttpResponse hashResponse = httpclient.execute(hashGet); HttpEntity hashentity = hashResponse.getEntity(); String formhash =""; if (hashentity != null) { String buffer = EntityUtils.toString(hashentity, "UTF-8"); int s = buffer.indexOf("id=\"formhash\" value=\""); s += 21; formhash = buffer.substring(s, s + 8); System.out.println("formhash:" + formhash); //end 读取整个页面内容 } hashGet.releaseConnection(); return formhash; } public final static HttpGet getGetMethod(String url){ HttpGet httpget = new HttpGet(url); httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;"); httpget.addHeader("Accept-Language", "zh-cn"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3"); httpget.addHeader("Accept-Charset", "utf-8"); httpget.addHeader("Keep-Alive", "30000"); httpget.addHeader("Connection", "Keep-Alive"); httpget.addHeader("Cache-Control", "no-cache"); return httpget; } /** * 获取Post方式HttpMethod * * @param url * 请求的URL * @return */ public final static HttpPost getPostMethod(String URL, HashMap<String, String> nameValuePair){ HttpPost post = new HttpPost(URL); post.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;"); post.addHeader("Accept-Language", "zh-cn"); post.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3"); post.addHeader("Accept-Charset", "utf-8"); post.addHeader("Keep-Alive", "300"); post.addHeader("Connection", "Keep-Alive"); post.addHeader("Cache-Control", "no-cache"); int size = nameValuePair.values().size(); if (size == 0) return post; NameValuePair[] param = new NameValuePair[size]; List<NameValuePair> params = new ArrayList<NameValuePair>(); Iterator iter = nameValuePair.entrySet().iterator(); while (iter.hasNext()){ Map.Entry entry = (Map.Entry) iter.next(); params.add(new BasicNameValuePair(String.valueOf(entry.getKey()),String.valueOf(entry.getValue()))); } post.setEntity(new UrlEncodedFormEntity(params,Consts.UTF_8)); return post; } public static YanBaoPo getYanBo(String baseUrl){ String resStr = httpRequest(baseUrl); if("".equals(resStr)) return null; String jsonStr = resStr.split("=")[1]; jsonStr = jsonStr.substring(0,jsonStr.length()-1); try { return new ObjectMapper().readValue(jsonStr, YanBaoPo.class); } catch (Exception e) { e.printStackTrace(); } return null; } public static String getBaseUrl(int pageSize,int page){ String url="http://data.eastmoney.com/reportold/data.aspx?style=ggyb&tp=&cg=&dt=m6&jg=&pageSize=%s&page=%s&jsname=tQZgsukS&rt="+System.currentTimeMillis()/1000; System.out.println("源url:"+String.format(url, pageSize,page)); return String.format(url, pageSize,page); } public static String httpRequest(String curl){ CloseableHttpClient httpclient = HttpClients.createDefault(); //httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5000); HttpGet httpget = new HttpGet(curl); try { CloseableHttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { int status = response.getStatusLine().getStatusCode(); return EntityUtils.toString(entity, "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } return ""; } public static List<YanBaoBean> convert2List(List<String> strList){ List<YanBaoBean> list = new ArrayList<YanBaoBean>(); if(strList!=null && strList.size()>=15){ for(String line : strList){ String code = line.split(",")[0]; String name = line.split(",")[1]; String uptime = line.split(",")[4]; if(uptime.split("-").length<=2) continue; String recommand = line.split(",")[5]; String recommandCompay = line.split(",")[7]; String yanbaoUrl = line.split(",")[13]; String yanbaoTitle = line.split(",")[14]; String yanbaoContent = "http://data.eastmoney.com/report/"+uptime.replace("-","")+"/"+yanbaoUrl+".html"; yanbaoContent = getYanbaoComment(yanbaoContent); list.add(new YanBaoBean(code,name,uptime,recommand,recommandCompay,yanbaoUrl,yanbaoTitle,yanbaoContent)); } } return list; } /** * 获取博客上的文章标题和链接 */ public static String getYanbaoComment(String commentUrl) { try { Document yanbaoDoc = Jsoup.connect(commentUrl).timeout(5000).get(); Element yanbaoElement = yanbaoDoc.getElementById("ContentBody"); String yanbaoContent = yanbaoElement.html().split("<!-- EM_StockImg_End -->")[1]; yanbaoContent = yanbaoContent.replace("<p>", "").replace("</p>", "\r\n"); System.out.println("研报内容:"+yanbaoContent); return yanbaoContent; } catch (IOException e) { e.printStackTrace(); } return ""; } }
apache-2.0
ChronixDB/chronix.server
chronix-server-type-metric/src/main/java/de/qaware/chronix/solr/type/metric/MetricType.java
6985
/* * Copyright (C) 2018 QAware GmbH * * 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 de.qaware.chronix.solr.type.metric; import de.qaware.chronix.server.functions.ChronixFunction; import de.qaware.chronix.server.types.ChronixTimeSeries; import de.qaware.chronix.server.types.ChronixType; import de.qaware.chronix.solr.type.metric.functions.aggregations.Avg; import de.qaware.chronix.solr.type.metric.functions.aggregations.Count; import de.qaware.chronix.solr.type.metric.functions.aggregations.Difference; import de.qaware.chronix.solr.type.metric.functions.aggregations.First; import de.qaware.chronix.solr.type.metric.functions.aggregations.Integral; import de.qaware.chronix.solr.type.metric.functions.aggregations.Last; import de.qaware.chronix.solr.type.metric.functions.aggregations.Max; import de.qaware.chronix.solr.type.metric.functions.aggregations.Min; import de.qaware.chronix.solr.type.metric.functions.aggregations.Percentile; import de.qaware.chronix.solr.type.metric.functions.aggregations.Range; import de.qaware.chronix.solr.type.metric.functions.aggregations.SignedDifference; import de.qaware.chronix.solr.type.metric.functions.aggregations.StdDev; import de.qaware.chronix.solr.type.metric.functions.aggregations.Sum; import de.qaware.chronix.solr.type.metric.functions.analyses.Frequency; import de.qaware.chronix.solr.type.metric.functions.analyses.Outlier; import de.qaware.chronix.solr.type.metric.functions.analyses.Trend; import de.qaware.chronix.solr.type.metric.functions.transformation.Add; import de.qaware.chronix.solr.type.metric.functions.transformation.Bottom; import de.qaware.chronix.solr.type.metric.functions.transformation.Derivative; import de.qaware.chronix.solr.type.metric.functions.transformation.Distinct; import de.qaware.chronix.solr.type.metric.functions.transformation.Divide; import de.qaware.chronix.solr.type.metric.functions.transformation.MovingAverage; import de.qaware.chronix.solr.type.metric.functions.transformation.NonNegativeDerivative; import de.qaware.chronix.solr.type.metric.functions.transformation.SampleMovingAverage; import de.qaware.chronix.solr.type.metric.functions.transformation.Scale; import de.qaware.chronix.solr.type.metric.functions.transformation.Subtract; import de.qaware.chronix.solr.type.metric.functions.transformation.Timeshift; import de.qaware.chronix.solr.type.metric.functions.transformation.Top; import de.qaware.chronix.solr.type.metric.functions.transformation.Vectorization; import de.qaware.chronix.timeseries.MetricTimeSeries; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.solr.common.SolrDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * Implementation of the metric type * * @author f.lautenschlager */ public class MetricType implements ChronixType<MetricTimeSeries> { private static final Logger LOGGER = LoggerFactory.getLogger(MetricType.class); @Override public String getType() { return "metric"; } @Override public ChronixTimeSeries<MetricTimeSeries> convert(String joinKey, List<SolrDocument> records, long queryStart, long queryEnd, boolean rawDataIsRequested) { MetricTimeSeries metricTimeSeries = SolrDocumentBuilder.reduceDocumentToTimeSeries(queryStart, queryEnd, records, rawDataIsRequested); return new ChronixMetricTimeSeries(joinKey, metricTimeSeries); } @Override public ChronixFunction<MetricTimeSeries> getFunction(String function) { switch (function) { //Aggregations case "avg": return new Avg(); case "min": return new Min(); case "max": return new Max(); case "sum": return new Sum(); case "count": return new Count(); case "dev": return new StdDev(); case "last": return new Last(); case "first": return new First(); case "range": return new Range(); case "diff": return new Difference(); case "sdiff": return new SignedDifference(); case "p": return new Percentile(); case "integral": return new Integral(); case "trend": return new Trend(); //Transformations case "add": return new Add(); case "sub": return new Subtract(); case "vector": return new Vectorization(); case "bottom": return new Bottom(); case "top": return new Top(); case "movavg": return new MovingAverage(); case "smovavg": return new SampleMovingAverage(); case "scale": return new Scale(); case "divide": return new Divide(); case "derivative": return new Derivative(); case "nnderivative": return new NonNegativeDerivative(); case "timeshift": return new Timeshift(); case "distinct": return new Distinct(); //Analyses case "outlier": return new Outlier(); case "frequency": return new Frequency(); //TODO: fix this for future releases // case "fastdtw": // return new FastDtw(args); default: LOGGER.warn("{} is not part of the MetricType. Return 'null'. Maybe its a plugin?", function); return null; } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MetricType rhs = (MetricType) obj; return new EqualsBuilder() .append(this.getType(), rhs.getType()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(getType()) .toHashCode(); } }
apache-2.0
aleroddepaz/soapuimodel
src/main/java/org/aleroddepaz/soapuimodel/MockService.java
3563
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.04.27 at 05:36:21 PM CEST // package org.aleroddepaz.soapuimodel; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for MockService complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MockService"> * &lt;complexContent> * &lt;extension base="{http://eviware.com/soapui/config}BaseMockService"> * &lt;sequence> * &lt;element name="mockOperation" type="{http://eviware.com/soapui/config}MockOperation" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="incomingWss" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="outgoingWss" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MockService", propOrder = { "mockOperation" }) public class MockService extends BaseMockService { protected List<MockOperation> mockOperation; @XmlAttribute(name = "incomingWss") protected String incomingWss; @XmlAttribute(name = "outgoingWss") protected String outgoingWss; /** * Gets the value of the mockOperation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the mockOperation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMockOperation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MockOperation } * * */ public List<MockOperation> getMockOperation() { if (mockOperation == null) { mockOperation = new ArrayList<MockOperation>(); } return this.mockOperation; } /** * Gets the value of the incomingWss property. * * @return * possible object is * {@link String } * */ public String getIncomingWss() { return incomingWss; } /** * Sets the value of the incomingWss property. * * @param value * allowed object is * {@link String } * */ public void setIncomingWss(String value) { this.incomingWss = value; } /** * Gets the value of the outgoingWss property. * * @return * possible object is * {@link String } * */ public String getOutgoingWss() { return outgoingWss; } /** * Sets the value of the outgoingWss property. * * @param value * allowed object is * {@link String } * */ public void setOutgoingWss(String value) { this.outgoingWss = value; } }
apache-2.0
IHTSDO/MLDS
src/main/java/ca/intelliware/ihtsdo/mlds/service/CommercialUsageAuditEvents.java
1845
package ca.intelliware.ihtsdo.mlds.service; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import ca.intelliware.ihtsdo.mlds.domain.CommercialUsage; import ca.intelliware.ihtsdo.mlds.domain.PersistentAuditEvent; import com.google.common.collect.Maps; @Service public class CommercialUsageAuditEvents { public static final String EVENT_USAGE_CREATED = "USAGE_CREATED"; public static final String EVENT_USAGE_APPROVAL_STATE_CHANGED = "USAGE_APPROVAL_STATE_CHANGED"; @Resource AuditEventService auditEventService; private Map<String, String> createAuditData(CommercialUsage usage) { Map<String,String> auditData = Maps.newHashMap(); auditData.put("usage.type", ""+usage.getType()); auditData.put("usage.commercialUsageId", ""+usage.getCommercialUsageId()); auditData.put("usage.period.start", ""+usage.getStartDate()); auditData.put("usage.period.end", ""+usage.getEndDate()); return auditData; } public void logCreationOf(CommercialUsage usage) { Map<String, String> auditData = createAuditData(usage); logEvent(usage, EVENT_USAGE_CREATED, auditData); } public void logUsageReportStateChange(CommercialUsage usage) { Map<String, String> auditData = createAuditData(usage); auditData.put("usage.approvalState", ""+usage.getState()); logEvent(usage, EVENT_USAGE_APPROVAL_STATE_CHANGED, auditData); } private void logEvent(CommercialUsage usage, String eventType, Map<String, String> auditData) { PersistentAuditEvent auditEvent = auditEventService.createAuditEvent(eventType, auditData); auditEvent.setCommercialUsageId(usage.getCommercialUsageId()); if (usage.getAffiliate() != null) { auditEvent.setAffiliateId(usage.getAffiliate().getAffiliateId()); } auditEventService.logAuditableEvent(auditEvent); } }
apache-2.0
kloiasoft/eventapis
emon-lib/src/main/java/com/kloia/eventapis/api/emon/domain/ServiceData.java
1540
package com.kloia.eventapis.api.emon.domain; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; @Data @AllArgsConstructor @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class ServiceData implements Serializable { private static final long serialVersionUID = 2401532791975588L; private String serviceName; private Map<Integer, Partition> partitions = new HashMap<>(); public ServiceData(String serviceName, List<Partition> partitionList) { this.serviceName = serviceName; this.setPartitions(partitionList); } public static ServiceData createServiceData(String consumer, List<Partition> value) { return new ServiceData(consumer, value.stream().collect(Collectors.toMap(Partition::getNumber, Function.identity()))); } public Partition getPartition(int number) { if (partitions != null) return partitions.get(number); else return null; } public Partition setPartition(Partition partition) { return partitions.put(partition.getNumber(), partition); } public void setPartitions(List<Partition> partitionList) { partitions = partitionList.stream().collect(Collectors.toMap(Partition::getNumber, Function.identity())); } }
apache-2.0
Berico-Technologies/CLAVIN
src/main/java/com/novetta/clavin/resolver/multipart/SearchLevel.java
5735
/*##################################################################### * * CLAVIN (Cartographic Location And Vicinity INdexer) * --------------------------------------------------- * * Copyright (C) 2012-2013 Berico Technologies * http://clavin.bericotechnologies.com * * ==================================================================== * * 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. * * ==================================================================== * * SearchLevel.java * *###################################################################*/ package com.novetta.clavin.resolver.multipart; import com.novetta.clavin.gazetteer.FeatureClass; import com.novetta.clavin.gazetteer.FeatureCode; import com.novetta.clavin.gazetteer.GeoName; import com.novetta.clavin.gazetteer.query.QueryBuilder; /** * A roll-up of feature classes and codes that assists in * searching for locations that fall into a particular category. */ public enum SearchLevel { COUNTRY, ADMIN1, ADMIN2, ADMIN3, ADMIN4, ADMINX, CITY; public static SearchLevel forGeoName(final GeoName name) { SearchLevel level = null; if (name != null) { if (name.isTopLevelAdminDivision()) { level = COUNTRY; } else if (name.getFeatureClass() == FeatureClass.A) { switch (name.getFeatureCode()) { case ADM1: case ADM1H: case TERR: case PRSH: level = ADMIN1; break; case ADM2: case ADM2H: level = ADMIN2; break; case ADM3: case ADM3H: level = ADMIN3; break; case ADM4: case ADM4H: level = ADMIN4; break; case ADM5: case ADMD: case ADMDH: level = ADMINX; break; default: // The level will default to null. } } else if (name.getFeatureClass() == FeatureClass.P) { level = CITY; } } return level; } public QueryBuilder apply(final QueryBuilder builder) { builder.clearFeatureCodes(); switch (this) { case COUNTRY: builder.addCountryCodes(); break; case ADMIN1: builder.addFeatureCodes(FeatureCode.ADM1, FeatureCode.ADM1H, FeatureCode.TERR, FeatureCode.PRSH); break; case ADMIN2: builder.addFeatureCodes(FeatureCode.ADM2, FeatureCode.ADM2H); break; case ADMIN3: builder.addFeatureCodes(FeatureCode.ADM3, FeatureCode.ADM3H); break; case ADMIN4: builder.addFeatureCodes(FeatureCode.ADM4, FeatureCode.ADM4H); break; case ADMINX: builder.addFeatureCodes(FeatureCode.ADM5, FeatureCode.ADMD, FeatureCode.ADMDH); break; case CITY: builder.addCityCodes(); break; } return builder; } public SearchLevel narrow() { switch (this) { case COUNTRY: return ADMIN1; case ADMIN1: return ADMIN2; case ADMIN2: return ADMIN3; case ADMIN3: return ADMIN4; case ADMIN4: return ADMINX; case ADMINX: return CITY; default: return null; } } public boolean canNarrow() { return narrow() != null; } public SearchLevel broaden() { switch (this) { case ADMIN1: return COUNTRY; case ADMIN2: return ADMIN1; case ADMIN3: return ADMIN2; case ADMIN4: return ADMIN3; case ADMINX: return ADMIN4; case CITY: return ADMINX; default: return null; } } public String getCode(final GeoName geoName) { switch (this) { case COUNTRY: return geoName.getPrimaryCountryCode().name(); case ADMIN1: return geoName.getAdmin1Code(); case ADMIN2: return geoName.getAdmin2Code(); case ADMIN3: return geoName.getAdmin3Code(); case ADMIN4: return geoName.getAdmin4Code(); default: return null; } } public boolean isAdmin() { switch (this) { case ADMIN1: case ADMIN2: case ADMIN3: case ADMIN4: case ADMINX: return true; default: return false; } } }
apache-2.0
mdavid/SuperSocket
ServerManager/v1.4/Client/WpfClient/ViewModel/InstanceViewModelBase.cs
436
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GalaSoft.MvvmLight; namespace SuperSocket.Management.Client.ViewModel { public abstract class InstanceViewModelBase : ViewModelBase { public InstanceViewModelBase(ServerViewModel server) { Server = server; } public ServerViewModel Server { get; private set; } } }
apache-2.0
dbflute-test/dbflute-test-dbms-db2
src/main/java/org/docksidestage/db2/dbflute/bsentity/BsWhiteTarget.java
7873
package org.docksidestage.db2.dbflute.bsentity; import java.util.List; import java.util.ArrayList; import org.dbflute.dbmeta.DBMeta; import org.dbflute.dbmeta.AbstractEntity; import org.dbflute.dbmeta.accessory.DomainEntity; import org.docksidestage.db2.dbflute.allcommon.DBMetaInstanceHandler; import org.docksidestage.db2.dbflute.exentity.*; /** * The entity of WHITE_TARGET as TABLE. <br> * <pre> * [primary-key] * TARGET_ID * * [column] * TARGET_ID, TARGET_NAME * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * * * [referrer table] * WHITE_REF_TARGET * * [foreign property] * * * [referrer property] * whiteRefTargetList * * [get/set template] * /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * Long targetId = entity.getTargetId(); * String targetName = entity.getTargetName(); * entity.setTargetId(targetId); * entity.setTargetName(targetName); * = = = = = = = = = =/ * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsWhiteTarget extends AbstractEntity implements DomainEntity { // =================================================================================== // Definition // ========== /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; // =================================================================================== // Attribute // ========= /** TARGET_ID: {PK, NotNull, DECIMAL(16)} */ protected Long _targetId; /** TARGET_NAME: {VARCHAR(256)} */ protected String _targetName; // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public DBMeta asDBMeta() { return DBMetaInstanceHandler.findDBMeta(asTableDbName()); } /** {@inheritDoc} */ public String asTableDbName() { return "WHITE_TARGET"; } // =================================================================================== // Key Handling // ============ /** {@inheritDoc} */ public boolean hasPrimaryKeyValue() { if (_targetId == null) { return false; } return true; } // =================================================================================== // Foreign Property // ================ // =================================================================================== // Referrer Property // ================= /** WHITE_REF_TARGET by TARGET_ID, named 'whiteRefTargetList'. */ protected List<WhiteRefTarget> _whiteRefTargetList; /** * [get] WHITE_REF_TARGET by TARGET_ID, named 'whiteRefTargetList'. * @return The entity list of referrer property 'whiteRefTargetList'. (NotNull: even if no loading, returns empty list) */ public List<WhiteRefTarget> getWhiteRefTargetList() { if (_whiteRefTargetList == null) { _whiteRefTargetList = newReferrerList(); } return _whiteRefTargetList; } /** * [set] WHITE_REF_TARGET by TARGET_ID, named 'whiteRefTargetList'. * @param whiteRefTargetList The entity list of referrer property 'whiteRefTargetList'. (NullAllowed) */ public void setWhiteRefTargetList(List<WhiteRefTarget> whiteRefTargetList) { _whiteRefTargetList = whiteRefTargetList; } protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import return new ArrayList<ELEMENT>(); } // =================================================================================== // Basic Override // ============== @Override protected boolean doEquals(Object obj) { if (obj instanceof BsWhiteTarget) { BsWhiteTarget other = (BsWhiteTarget)obj; if (!xSV(_targetId, other._targetId)) { return false; } return true; } else { return false; } } @Override protected int doHashCode(int initial) { int hs = initial; hs = xCH(hs, asTableDbName()); hs = xCH(hs, _targetId); return hs; } @Override protected String doBuildStringWithRelation(String li) { StringBuilder sb = new StringBuilder(); if (_whiteRefTargetList != null) { for (WhiteRefTarget et : _whiteRefTargetList) { if (et != null) { sb.append(li).append(xbRDS(et, "whiteRefTargetList")); } } } return sb.toString(); } @Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(xfND(_targetId)); sb.append(dm).append(xfND(_targetName)); if (sb.length() > dm.length()) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } @Override protected String doBuildRelationString(String dm) { StringBuilder sb = new StringBuilder(); if (_whiteRefTargetList != null && !_whiteRefTargetList.isEmpty()) { sb.append(dm).append("whiteRefTargetList"); } if (sb.length() > dm.length()) { sb.delete(0, dm.length()).insert(0, "(").append(")"); } return sb.toString(); } @Override public WhiteTarget clone() { return (WhiteTarget)super.clone(); } // =================================================================================== // Accessor // ======== /** * [get] TARGET_ID: {PK, NotNull, DECIMAL(16)} <br> * @return The value of the column 'TARGET_ID'. (basically NotNull if selected: for the constraint) */ public Long getTargetId() { checkSpecifiedProperty("targetId"); return _targetId; } /** * [set] TARGET_ID: {PK, NotNull, DECIMAL(16)} <br> * @param targetId The value of the column 'TARGET_ID'. (basically NotNull if update: for the constraint) */ public void setTargetId(Long targetId) { registerModifiedProperty("targetId"); _targetId = targetId; } /** * [get] TARGET_NAME: {VARCHAR(256)} <br> * @return The value of the column 'TARGET_NAME'. (NullAllowed even if selected: for no constraint) */ public String getTargetName() { checkSpecifiedProperty("targetName"); return _targetName; } /** * [set] TARGET_NAME: {VARCHAR(256)} <br> * @param targetName The value of the column 'TARGET_NAME'. (NullAllowed: null update allowed for no constraint) */ public void setTargetName(String targetName) { registerModifiedProperty("targetName"); _targetName = targetName; } }
apache-2.0
yuananf/presto
presto-main/src/main/java/com/facebook/presto/operator/HashSemiJoinOperator.java
6750
/* * 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 com.facebook.presto.operator; import com.facebook.presto.operator.SetBuilderOperator.SetSupplier; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import java.util.List; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static io.airlift.concurrent.MoreFutures.tryGetFutureValue; import static java.util.Objects.requireNonNull; public class HashSemiJoinOperator implements Operator { private final OperatorContext operatorContext; public static class HashSemiJoinOperatorFactory implements OperatorFactory { private final int operatorId; private final PlanNodeId planNodeId; private final SetSupplier setSupplier; private final List<Type> probeTypes; private final int probeJoinChannel; private final List<Type> types; private boolean closed; public HashSemiJoinOperatorFactory(int operatorId, PlanNodeId planNodeId, SetSupplier setSupplier, List<? extends Type> probeTypes, int probeJoinChannel) { this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); this.setSupplier = setSupplier; this.probeTypes = ImmutableList.copyOf(probeTypes); checkArgument(probeJoinChannel >= 0, "probeJoinChannel is negative"); this.probeJoinChannel = probeJoinChannel; this.types = ImmutableList.<Type>builder() .addAll(probeTypes) .add(BOOLEAN) .build(); } @Override public List<Type> getTypes() { return types; } @Override public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, HashSemiJoinOperator.class.getSimpleName()); return new HashSemiJoinOperator(operatorContext, setSupplier, probeTypes, probeJoinChannel); } @Override public void noMoreOperators() { closed = true; } @Override public OperatorFactory duplicate() { return new HashSemiJoinOperatorFactory(operatorId, planNodeId, setSupplier, probeTypes, probeJoinChannel); } } private final int probeJoinChannel; private final List<Type> types; private final ListenableFuture<ChannelSet> channelSetFuture; private ChannelSet channelSet; private Page outputPage; private boolean finishing; public HashSemiJoinOperator(OperatorContext operatorContext, SetSupplier channelSetFuture, List<Type> probeTypes, int probeJoinChannel) { this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); // todo pass in desired projection requireNonNull(channelSetFuture, "hashProvider is null"); requireNonNull(probeTypes, "probeTypes is null"); checkArgument(probeJoinChannel >= 0, "probeJoinChannel is negative"); this.channelSetFuture = channelSetFuture.getChannelSet(); this.probeJoinChannel = probeJoinChannel; this.types = ImmutableList.<Type>builder() .addAll(probeTypes) .add(BOOLEAN) .build(); } @Override public OperatorContext getOperatorContext() { return operatorContext; } @Override public List<Type> getTypes() { return types; } @Override public void finish() { finishing = true; } @Override public boolean isFinished() { return finishing && outputPage == null; } @Override public ListenableFuture<?> isBlocked() { return channelSetFuture; } @Override public boolean needsInput() { if (finishing || outputPage != null) { return false; } if (channelSet == null) { channelSet = tryGetFutureValue(channelSetFuture).orElse(null); } return channelSet != null; } @Override public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!finishing, "Operator is finishing"); checkState(channelSet != null, "Set has not been built yet"); checkState(outputPage == null, "Operator still has pending output"); // create the block builder for the new boolean column // we know the exact size required for the block BlockBuilder blockBuilder = BOOLEAN.createFixedSizeBlockBuilder(page.getPositionCount()); Page probeJoinPage = new Page(page.getBlock(probeJoinChannel)); // update hashing strategy to use probe cursor for (int position = 0; position < page.getPositionCount(); position++) { if (probeJoinPage.getBlock(0).isNull(position)) { if (channelSet.isEmpty()) { BOOLEAN.writeBoolean(blockBuilder, false); } else { blockBuilder.appendNull(); } } else { boolean contains = channelSet.contains(position, probeJoinPage); if (!contains && channelSet.containsNull()) { blockBuilder.appendNull(); } else { BOOLEAN.writeBoolean(blockBuilder, contains); } } } // add the new boolean column to the page outputPage = page.appendColumn(blockBuilder.build()); } @Override public Page getOutput() { Page result = outputPage; outputPage = null; return result; } }
apache-2.0
skobelev-dmitriy/HeadsHands
app/src/main/java/rf/digworld/headhands/injection/component/ApplicationComponent.java
893
package rf.digworld.headhands.injection.component; import android.app.Application; import android.content.Context; import com.squareup.otto.Bus; import javax.inject.Singleton; import dagger.Component; import rf.digworld.headhands.data.DataManager; import rf.digworld.headhands.data.local.DatabaseHelper; import rf.digworld.headhands.data.local.PreferencesHelper; import rf.digworld.headhands.data.remote.NetworkService; import rf.digworld.headhands.injection.ApplicationContext; import rf.digworld.headhands.injection.module.ApplicationModule; @Singleton @Component(modules = ApplicationModule.class) public interface ApplicationComponent { @ApplicationContext Context context(); Application application(); NetworkService ribotsService(); PreferencesHelper preferencesHelper(); DatabaseHelper databaseHelper(); DataManager dataManager(); Bus eventBus(); }
apache-2.0
chenxihoho/FirstFrame
003.Dapper/Dapper/OracleDBHelper.cs
63507
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Data.OracleClient; using System.Configuration; namespace Web.Utility.sqlHelper { #region Data Access Base Class /// <summary> /// Data Access Base Class /// </summary> public abstract class OracleDbHelper { protected static string connectionString = ConfigHelper.DBConnection; #region const protected const string str_isExistJBRWPackage = @" select count(*) from user_objects where object_type = 'PACKAGE' and object_name= 'RASEI' "; protected const string str_jbrwpackage = @" create or replace package RASEI is procedure GetPager ( row_from int, /*行开始*/ row_to int, /*行结束*/ p_SqlSelect varchar2, /*查询语句,含排序部分*/ p_OutRecordCount out int,/*返回总记录数*/ p_OutCursor out sys_refcursor ); procedure PROC_INSERT_DATA( TABLE_NAME nVARCHAR2, EXISTS_CONDITIONS nVARCHAR2, UPDATE_SQL nVARCHAR2, INSERT_SQL nVARCHAR2 ); end;"; protected const string str_jbrwpackage_body = @" create or replace package body RASEI as /*分页查询*/ procedure GetPager ( row_from int, /*行开始*/ row_to int, /*行结束*/ p_SqlSelect varchar2, /*查询语句,含排序部分*/ p_OutRecordCount out int,/*返回总记录数*/ p_OutCursor out sys_refcursor ) as v_sql varchar2(4000); v_count int; begin /*取记录总数*/ v_sql := 'select count(1) from (' || p_SqlSelect || ')'; execute immediate v_sql into v_count; p_OutRecordCount := v_count; /*执行分页查询*/ v_sql := 'SELECT * FROM ( SELECT A.*, rownum rn FROM ('|| p_SqlSelect ||') A WHERE rownum <= '|| to_char(row_to) || ' ) B WHERE rn >= ' || to_char(row_from) ; /*注意对rownum别名的使用,第一次直接用rownum,第二次一定要用别名rn*/ OPEN p_OutCursor FOR v_sql; end ; /*基础数据增删改*/ procedure PROC_INSERT_DATA( TABLE_NAME nVARCHAR2, EXISTS_CONDITIONS nVARCHAR2, UPDATE_SQL nVARCHAR2, INSERT_SQL nVARCHAR2) is ROW_CN NUMBER; STR_SQL VARCHAR2(1000); begin if(length(EXISTS_CONDITIONS)>0) then STR_SQL := 'SELECT COUNT(1) FROM '||TABLE_NAME||' WHERE '||EXISTS_CONDITIONS ; DBMS_OUTPUT.put_line(STR_SQL); EXECUTE IMMEDIATE STR_SQL into ROW_CN; IF(ROW_CN>0) THEN STR_SQL := 'UPDATE '|| TABLE_NAME||' '||UPDATE_SQL || ' WHERE '||EXISTS_CONDITIONS ; ELSE STR_SQL :='INSERT INTO '|| TABLE_NAME||INSERT_SQL; END IF; elsif(length(UPDATE_SQL)>0) then STR_SQL := 'UPDATE '|| TABLE_NAME||' '||UPDATE_SQL; elsif(length(INSERT_SQL)>0) then STR_SQL := 'INSERT INTO '|| TABLE_NAME||INSERT_SQL; end if; DBMS_OUTPUT.put_line(STR_SQL); EXECUTE IMMEDIATE STR_SQL; end; end ; "; private static void check_JBRWPackage() { if (GetSingle(str_isExistJBRWPackage).ToString() == "0") { ExecuteSql(str_jbrwpackage); ExecuteSql(str_jbrwpackage_body); } } #endregion public OracleDbHelper() { } #region 参数处理 /// <summary> /// 参数替换:得数参数时,各参数不得相互包涵 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="pas">参数</param> /// <returns></returns> public static string INIT_PARAMS_SQL(List<DParam> pas, string sql) { if (string.IsNullOrEmpty(sql.Trim())) return ""; sql = sqlLeach(sql.Trim()) + " "; foreach (DParam pa in pas) { string paramName = pa.paramName.Trim(); string cEnd = " "; int pos = sql.IndexOf(":" + paramName + cEnd); if (pos == -1) { cEnd = ","; pos = sql.IndexOf(":" + paramName + cEnd); } if (pos == -1) { cEnd = ")"; pos = sql.IndexOf(":" + paramName + cEnd); } if (pos == -1) { cEnd = "'"; pos = sql.IndexOf(":" + paramName + cEnd); } if (pos != -1) { string v = ""; switch ((OracleType)pa.fieldType) { case OracleType.Double: case OracleType.Int16: case OracleType.Int32: case OracleType.Float: case OracleType.Number: case OracleType.UInt16: case OracleType.UInt32: v = DBHelper.setNumFiled(pa.paramValue); break; case OracleType.DateTime: v = DBHelper.setOracleDateTime(pa.paramValue); break; default: v = DBHelper.setVarcharFiled(pa.paramValue); break; } sql = sql.Replace(":" + paramName + cEnd, v + cEnd) + " "; } } return sql.Trim(); } /// <summary> /// 参数替换:得数参数时,各参数不得相互包涵 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="pas">参数</param> /// <returns></returns> public static PARAMS_SQL INIT_PARAMS_SQL(string sql, List<DParam> pas) { if (string.IsNullOrEmpty(sql.Trim())) return null; PARAMS_SQL ps = new PARAMS_SQL(); ps.strSQl = sqlLeach(sql.Trim()) + " "; List<OracleParameter> dps = new List<OracleParameter>(); foreach (DParam pa in pas) { pa.paramName = pa.paramName.Trim(); OracleParameter np = new OracleParameter(pa.paramName, pa.fieldType); np.Value = pa.paramValue; dps.Add(np); } ps.strSQl = ps.strSQl.Trim(); ps.Params = dps.ToArray(); return ps; } #endregion #region 公用方法 private static string sqlLeach(string strSql) { return strSql.Replace("\r\n", " ").Replace("\n", " ").Replace("&", "\\&").TrimEnd();//.TrimEnd(';'); } /// <summary> /// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand</returns> private static OracleCommand BuildQueryCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters) { return BuildQueryCommand(null, storedProcName, parameters); } /// <summary> /// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand</returns> private static OracleCommand BuildQueryCommand(OracleTransaction sqlTrans, OracleConnection connection, string storedProcName, IDataParameter[] parameters) { OracleCommand command = new OracleCommand(storedProcName, connection, sqlTrans); command.CommandType = CommandType.StoredProcedure; foreach (OracleParameter parameter in parameters) command.Parameters.Add(parameter); return command; } /// <summary> /// 创建 OracleCommand 对象实例(用来返回一个整数值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand 对象实例</returns> private static OracleCommand BuildIntCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters) { OracleCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add(new OracleParameter("ReturnValue", OracleType.Int32, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string cmdText, OracleParameter[] cmdParms) { try { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = sqlLeach(cmdText); if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (OracleParameter parm in cmdParms) { if((parm.Value==null|| parm.Value.ToString()=="") && (parm.DbType == DbType.Date || parm.DbType == DbType.DateTime || parm.DbType == DbType.DateTime2)) { parm.DbType= DbType.String; } if ((parm.Value==null|| parm.Value.ToString().Trim().Replace("'","")=="")&& (parm.DbType == DbType.Decimal || parm.DbType == DbType.Double || parm.DbType == DbType.Int16 || parm.DbType == DbType.Int32 || parm.DbType == DbType.Int64 || parm.DbType == DbType.UInt16|| parm.DbType == DbType.UInt32|| parm.DbType == DbType.UInt64)) { parm.Value = 0; } cmd.Parameters.Add(parm); } } } catch (Exception ex) { throw ex; } } /// <summary> /// 初始化数据库连接 /// </summary> /// <param name="connectionString"></param> /// <returns></returns> public static OracleConnection initDBConnect(string connectionString) { return new OracleConnection(connectionString); ; } /// <summary> /// 初始化数据库连接 /// </summary> /// <returns></returns> public static OracleConnection initDBConnect() { return new OracleConnection(connectionString); ; } /// <summary> /// 初始化事务,并打开数据连接 /// </summary> /// <returns></returns> public static OracleTransaction initTranc() { OracleConnection connection = initDBConnect(); if (connection.State == System.Data.ConnectionState.Closed) connection.Open(); return connection.BeginTransaction(); } /// <summary> /// 关闭数据库连接 /// </summary> /// <param name="connection"></param> public static void ConnectionClose(OracleConnection connection) { if (connection != null && connection.State == ConnectionState.Open) connection.Close(); } #endregion #region Exists /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="SQLString">计算查询结果语句</param> /// <param name="cmdParms">脚本参数</param> /// <returns>查询结果(object)</returns> public static object GetSingle(OracleTransaction sqlTrans, string SQLString, params OracleParameter[] cmdParms) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 OracleCommand cmd = new OracleCommand(); try { PrepareCommand(cmd, hasInputTransaction == true ? sqlTrans.Connection : initDBConnect(), sqlTrans, sqlLeach(SQLString), cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { if (hasInputTransaction == false) ConnectionClose(cmd.Connection); cmd.Dispose(); } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { return GetSingle(null, SQLString, new OracleParameter[] { }); } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="SQLString">脚本</param> /// <returns></returns> public static object GetSingle(OracleTransaction sqlTrans, string SQLString) { return GetSingle(sqlTrans, SQLString, new OracleParameter[] { }); } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="SQLString">脚本</param> /// <param name="sqlParams">脚本参数</param> /// <returns></returns> public static object GetSingle(string SQLString, List<OracleParameter> sqlParams) { return GetSingle(null, SQLString, sqlParams); } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="SQLString">脚本</param> /// <param name="sqlParams">脚本参数</param> /// <returns></returns> public static object GetSingle(OracleTransaction sqlTrans, string SQLString, List<OracleParameter> sqlParams) { return GetSingle(sqlTrans, SQLString, sqlParams.ToArray()); } public static bool Exists(string strSql) { return Exists(null, strSql, new OracleParameter[] { }); } public static bool Exists(string strSql, List<OracleParameter> cmdParms) { return Exists(null, strSql, cmdParms.ToArray()); } public static bool Exists(OracleTransaction sqlTrans, string strSql, List<OracleParameter> cmdParms) { return Exists(sqlTrans, strSql, cmdParms.ToArray()); } public static bool Exists(OracleTransaction sqlTrans, string strSql, params OracleParameter[] cmdParms) { object obj = GetSingle(sqlTrans, strSql, cmdParms); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) return false; else return true; } #endregion #region 执行简单SQL语句 /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static string ExecuteSqlTran(ArrayList SQLStringList) { string RetrunValue = ""; string strsql = ""; using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection = connection; OracleTransaction tx = connection.BeginTransaction(); cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = sqlLeach(strsql); cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (System.Data.OracleClient.OracleException E) { tx.Rollback(); RetrunValue = strsql + "\n" + E.ToString(); } finally { cmd.Dispose(); connection.Close(); } } return RetrunValue; } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static string ExecuteSqlTran_ReTrim(ArrayList SQLStringList) { string RetrunValue = ""; string strsql = ""; using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); OracleCommand cmd = new OracleCommand(); try { cmd.Connection = connection; OracleTransaction tx = connection.BeginTransaction(); cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = sqlLeach(strsql); cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (System.Data.OracleClient.OracleException E) { tx.Rollback(); RetrunValue = E.ToString(); } } catch (System.Data.OracleClient.OracleException E) { RetrunValue = strsql + "\n" + E.ToString(); } finally { cmd.Dispose(); connection.Close(); } } return RetrunValue; } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand cmd = new OracleCommand(); try { cmd = new OracleCommand(sqlLeach(SQLString), connection); System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter("@content", OracleType.NVarChar); myParameter.Value = content; cmd.Parameters.Add(myParameter); connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.OracleClient.OracleException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入BLOB的字段 /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">字节,数据库的字段类型为BLOB的情况</param> /// <returns></returns> public static int ExecuteSqlInsertBLOB(string strSQL, byte[] fs) { using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); OracleCommand cmd = new OracleCommand(); OracleTransaction tx = connection.BeginTransaction(); try { //cmd = new OracleCommand(strSQL, connection); //启动一个事务 cmd = connection.CreateCommand(); cmd.Transaction = tx; //这里是关键,他定义了一个命令对象的t-sql语句,通过dmbs_lob来创建一个零时对象,这个对象的类型为blob,并存放在变量xx中,然后将xx的值付给外传参数tmpblob cmd.CommandText = "declare xx blob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;"; //构造外传参数对象,并加入到命令对象的参数集合中 cmd.Parameters.Add(new OracleParameter("tempblob", OracleType.Blob)).Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); //构造OracleLob对象,他的值为tmpblob外传参数的值 OracleLob tempLob = (OracleLob)cmd.Parameters[0].Value; //指定tempLob的访问模式,并开始操作二进制数据 tempLob.BeginBatch(OracleLobOpenMode.ReadWrite); //将二进制流byte数组集合写入到tmpLob里 tempLob.Write(fs, 0, fs.Length); tempLob.EndBatch(); cmd.Parameters.Clear(); // cmd.CommandText = sqlLeach(strSQL); cmd.CommandType = CommandType.Text; //创建存储过程的Blob参数,并指定Blob参数的值为tempLob(表示服务器上大型对象二进制数据类型),并将Blob参数加入到command对象的参数集合里 OracleParameter tmp_blob = new OracleParameter(":fs", OracleType.Blob); tmp_blob.Value = tempLob; cmd.Parameters.Add(tmp_blob); int rows = cmd.ExecuteNonQuery(); tx.Commit(); return rows; } catch (System.Data.OracleClient.OracleException E) { tx.Rollback(); cmd.Dispose(); connection.Close(); throw new Exception(E.Message + strSQL); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>OracleDataReader</returns> public static OracleDataReader ExecuteReader(string strSQL) { OracleConnection connection = new OracleConnection(connectionString); OracleCommand cmd = new OracleCommand(sqlLeach(strSQL), connection); try { connection.Open(); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { cmd.Dispose(); connection.Close(); } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程 返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="storedProcName">存储过程名</param> /// <param name="cmdParms">存储过程参数</param> /// <returns>OracleDataReader</returns> public static OracleDataReader ReaderProcedure(OracleTransaction sqlTrans, string storedProcName, IDataParameter[] cmdParms) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 OracleDataReader returnReader; OracleCommand cmd = BuildQueryCommand(sqlTrans, hasInputTransaction == true ? sqlTrans.Connection : initDBConnect(), sqlLeach(storedProcName), cmdParms); try { cmd.CommandType = CommandType.StoredProcedure; if (hasInputTransaction) returnReader = cmd.ExecuteReader(); else returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Dispose(); return returnReader; } catch (Exception ex) { throw new Exception(ex.Message); } finally { if (hasInputTransaction == false) ConnectionClose(cmd.Connection); cmd.Dispose(); } } /// <summary> /// 执行存储过程 返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="storedProcName">存储过程名</param> /// <param name="cmdParms">存储过程参数</param> /// <returns>OracleDataReader</returns> public static OracleDataReader ReaderProcedure(string storedProcName, IDataParameter[] cmdParms) { return ReaderProcedure(null, storedProcName, cmdParms); } public static bool RunProcedure(OracleTransaction sqlTrans, string SQLString) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 if (hasInputTransaction == false) sqlTrans = initTranc(); OracleCommand cmd = new OracleCommand(); cmd.Transaction = sqlTrans; cmd.Connection = sqlTrans.Connection; cmd.CommandType = CommandType.StoredProcedure; bool isSuccess = false; try { cmd.CommandText = sqlLeach(SQLString); cmd.ExecuteNonQuery(); isSuccess = true; } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { if (hasInputTransaction == false) { if (isSuccess == false) sqlTrans.Rollback(); else sqlTrans.Commit(); ConnectionClose(cmd.Connection); } cmd.Dispose(); } return isSuccess; } public static bool RunProcedure(string SQLString) { return RunProcedure(null, SQLString); } public static bool RunProcedure(ArrayList SQLStrings) { OracleTransaction tranc = initTranc(); bool isSuccess = false; try { foreach (string sql in SQLStrings) { isSuccess = RunProcedure(tranc, sql); if (isSuccess == false) break; } } catch (Exception exp) { throw new Exception(exp.Message); } finally { if (isSuccess) tranc.Commit(); else tranc.Rollback(); ConnectionClose(tranc.Connection); } return isSuccess; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="procName">存储过程名</param> /// <param name="cmdParms">存储过程参数</param> /// <returns>执行结果:成功,失败</returns> public static bool RunProcedure(string procName, List<OracleParameter> cmdParms) { return RunProcedure(null, procName, cmdParms.ToArray()); } public static bool RunProcedure(OracleTransaction sqlTrans, string procName, IDataParameter[] cmdParms) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 if (hasInputTransaction == false) sqlTrans = initTranc(); bool isSuccess = false; try { using (OracleCommand cmd = BuildQueryCommand(sqlTrans, sqlTrans.Connection, procName, cmdParms)) { cmd.ExecuteNonQuery(); isSuccess = true; } } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { if (hasInputTransaction == false) { if (isSuccess == false) sqlTrans.Rollback(); else sqlTrans.Commit(); ConnectionClose(sqlTrans.Connection); } } return isSuccess; } public bool RunProcedure(OracleTransaction sqlTrans, List<PARAMS_SQL> params_sql) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 if (hasInputTransaction == false) sqlTrans = initTranc(); bool isSuccess = false; try { foreach (PARAMS_SQL ps in params_sql) { isSuccess = RunProcedure(sqlTrans, ps.strSQl, ps.SqlParams); if (isSuccess == false) break; } } catch (Exception exp) { throw exp; } finally { if (hasInputTransaction == false) { if (isSuccess) sqlTrans.Commit(); else sqlTrans.Rollback(); ConnectionClose(sqlTrans.Connection); } } return isSuccess; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="sqlTrans">事务</param> /// <param name="procName">存储过程名</param> /// <param name="cmdParms">存储过程参数</param> /// <returns>执行结果:成功,失败</returns> public static DataSet RunProcedure(OracleTransaction sqlTrans, string storedProcName, IDataParameter[] cmdParms, string tableName) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 if (hasInputTransaction == false) sqlTrans = initTranc(); DataSet Dset = new DataSet(); bool isSuccess = false; try { using (OracleCommand cmd = BuildQueryCommand(sqlTrans, sqlTrans.Connection, storedProcName, cmdParms)) { OracleDataAdapter ODAdp = new OracleDataAdapter(cmd); if (string.IsNullOrEmpty(tableName)) ODAdp.Fill(Dset, "PROJECT"); else ODAdp.Fill(Dset, tableName); ODAdp.Dispose(); } isSuccess = true; } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { if (hasInputTransaction == false) { if (isSuccess == false) sqlTrans.Rollback(); else sqlTrans.Commit(); ConnectionClose(sqlTrans.Connection); } } return Dset; } public static DataSet RunProcedure(string storedProcName, List<OracleParameter> parameters, string tableName) { return RunProcedure(null, storedProcName, parameters.ToArray(), tableName); } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) { return RunProcedure(null, storedProcName, parameters, tableName); } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters) { return RunProcedure(null, storedProcName, parameters, null); } /// <summary> /// 执行存储过程,返回影响的行数 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="rowsAffected">影响的行数</param> /// <returns></returns> public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (OracleConnection connection = new OracleConnection(connectionString)) { try { int result; connection.Open(); OracleCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters["ReturnValue"].Value; connection.Close(); return result; } catch (Exception ex) { throw ex; } finally { connection.Close(); } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (OracleConnection conn = new OracleConnection(connectionString)) { conn.Open(); using (OracleTransaction trans = conn.BeginTransaction()) { OracleCommand cmd = new OracleCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); OracleParameter[] cmdParms = (OracleParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, sqlLeach(cmdText), cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } finally { cmd.Dispose(); conn.Close(); } } } } public static void ExecuteSqlTran(Hashtable SQLStringList1, Hashtable SQLStringList2) { using (OracleConnection conn = new OracleConnection(connectionString)) { conn.Open(); using (OracleTransaction trans = conn.BeginTransaction()) { OracleCommand cmd = new OracleCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList1) { //同一个model多条记录的批量操作,sql重复 string cmdText = myDE.Value.ToString(); OracleParameter[] cmdParms = (OracleParameter[])myDE.Key; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } //循环 foreach (DictionaryEntry myDE in SQLStringList2) { //同一个model多条记录的批量操作,sql重复 string cmdText = myDE.Value.ToString(); OracleParameter[] cmdParms = (OracleParameter[])myDE.Key; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } finally { cmd.Dispose(); conn.Close(); } } } } public static void ExecuteSqlTran(Hashtable SQLStringList, bool isReversed) { if (isReversed) { using (OracleConnection conn = new OracleConnection(connectionString)) { conn.Open(); using (OracleTransaction trans = conn.BeginTransaction()) { OracleCommand cmd = new OracleCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { //同一个model多条记录的批量操作,sql重复 string cmdText = myDE.Value.ToString(); OracleParameter[] cmdParms = (OracleParameter[])myDE.Key; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } finally { cmd.Dispose(); conn.Close(); } } } } else ExecuteSqlTran(SQLStringList); } #endregion #region Query 执行查询语句,返回DataSet public static DataSet Query(OracleTransaction sqlTrans, string SQLString, params OracleParameter[] cmdParms) { return Query(sqlTrans, SQLString, "Project", cmdParms); } public static DataSet Query(OracleTransaction sqlTrans, string SQLString, string strTableName, params OracleParameter[] cmdParms) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 OracleCommand cmd = new OracleCommand(); DataSet ds = new DataSet(); try { PrepareCommand(cmd, hasInputTransaction == true ? sqlTrans.Connection : initDBConnect(), sqlTrans, sqlLeach(SQLString), cmdParms); using (OracleDataAdapter da = new OracleDataAdapter(cmd)) { da.Fill(ds, strTableName); cmd.Parameters.Clear(); } } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { if (hasInputTransaction == false) ConnectionClose(cmd.Connection); cmd.Dispose(); } return ds; } public static DataSet Query(string SQLString) { return Query(null, SQLString, new OracleParameter[] { }); } public static DataSet Query(OracleTransaction sqlTrans, string SQLString) { return Query(sqlTrans, SQLString, new OracleParameter[] { }); } public static DataSet Query(string SQLString, List<OracleParameter> cmdParms) { return Query(null, SQLString, cmdParms.ToArray()); } public static DataSet Query(string SQLString, params OracleParameter[] cmdParms) { return Query(null, SQLString, cmdParms); } public static DataSet Query(OracleTransaction sqlTrans, string SQLString, List<OracleParameter> cmdParms) { return Query(sqlTrans, SQLString, cmdParms.ToArray()); } public static DataSet Query(OracleTransaction sqlTrans, string SQLString, string strTableName, List<OracleParameter> cmdParms) { return Query(sqlTrans, SQLString, strTableName, cmdParms.ToArray()); } #endregion #region QueryTable 执行查询语句,返回DataTable public static DataTable QueryTable(OracleTransaction sqlTrans, string SQLString, params OracleParameter[] cmdParms) { return QueryTable(sqlTrans, SQLString, "", cmdParms); } public static DataTable QueryTable(OracleTransaction sqlTrans, string SQLString, string strTableName, params OracleParameter[] cmdParms) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 OracleCommand cmd = new OracleCommand(); DataTable dt = new DataTable(); try { PrepareCommand(cmd, hasInputTransaction == true ? sqlTrans.Connection : initDBConnect(), sqlTrans, sqlLeach(SQLString), cmdParms); using (OracleDataAdapter da = new OracleDataAdapter(cmd)) { da.Fill(dt); if (!string.IsNullOrEmpty(strTableName) && dt != null) dt.TableName = strTableName; } } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { if (hasInputTransaction == false) ConnectionClose(cmd.Connection); cmd.Dispose(); } return dt; } public static DataTable QueryTable(string SQLString) { return QueryTable(null, SQLString, new OracleParameter[] { }); } public static DataTable QueryTable(OracleTransaction sqlTrans, string SQLString) { return QueryTable(sqlTrans, SQLString, new OracleParameter[] { }); } public static DataTable QueryTable(string SQLString, List<OracleParameter> cmdParms) { return QueryTable(null, SQLString, cmdParms.ToArray()); } public static DataTable QueryTable(string SQLString, params OracleParameter[] cmdParms) { return QueryTable(null, SQLString, cmdParms); } public static DataTable QueryTable(OracleTransaction sqlTrans, string SQLString, List<OracleParameter> cmdParms) { return QueryTable(sqlTrans, SQLString, cmdParms.ToArray()); } public static DataTable QueryTable(OracleTransaction sqlTrans, string SQLString, string strTableName, List<OracleParameter> cmdParms) { return QueryTable(sqlTrans, SQLString, strTableName, cmdParms.ToArray()); } #endregion #region PagingQuery 执行查询语句,返回DataTable /// <summary> /// 执行查询语句,返回DataTable /// </summary> /// <param name="SQLString">查询语句</param> /// <param name="page_size">每页显示行数</param> /// <param name="page_no">当前第几页</param> /// <returns>DataSet</returns> public static DataTable PagingQuery(string strSql, int page_size, int page_no) { int row_from = (page_no - 1) * page_size + 1, row_to = page_no * page_size; return PagingQuery(row_from, row_to, strSql); } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <param name="page_size">开始行</param> /// <param name="page_no">结束行</param> /// <returns>DataSet</returns> public static DataTable PagingQuery(int row_from, int row_to, string strSql) { if (row_to == 0) { DataTable dt = QueryTable(strSql); if (dt != null) dt.TableName = dt.Rows.Count.ToString(); return dt; } else { OracleParameter[] param = new OracleParameter[]{ new OracleParameter("row_from", OracleType.Number), new OracleParameter("row_to", OracleType.Number), new OracleParameter("p_SqlSelect", OracleType.VarChar), new OracleParameter("p_OutRecordCount", OracleType.Number), new OracleParameter("p_OutCursor", OracleType.Cursor) }; param[0].Value = row_from; param[1].Value = row_to; param[2].Value = strSql; param[3].Direction = ParameterDirection.Output; param[4].Direction = ParameterDirection.Output; check_JBRWPackage(); DataSet ds = RunProcedure("rasei.GetPager", param, "searcher"); string rowCount = param[3].Value.ToString(); if (rowCount == "0") return null; else { ds.Tables[0].TableName = rowCount; return ds.Tables[0]; } } } #endregion #region ExecuteSql 执行增删改脚本方法 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(OracleTransaction sqlTrans, string SQLString, params OracleParameter[] cmdParms) { bool hasInputTransaction = sqlTrans != null;//是否传入事务 OracleCommand cmd = new OracleCommand(); DataTable dt = new DataTable(); int rows = -1; try { PrepareCommand(cmd, hasInputTransaction == true ? sqlTrans.Connection : initDBConnect(), sqlTrans, sqlLeach(SQLString), cmdParms); using (OracleDataAdapter da = new OracleDataAdapter(cmd)) { rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } catch (System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } finally { if (hasInputTransaction == false) ConnectionClose(cmd.Connection); cmd.Dispose(); } return rows; } public static int ExecuteSql(string SQLString) { return ExecuteSql(null, SQLString, new OracleParameter[] { }); } public static int ExecuteSql(OracleTransaction sqlTrans, string SQLString) { return ExecuteSql(sqlTrans, SQLString, new OracleParameter[] { }); } public static int ExecuteSql(string SQLString, List<OracleParameter> cmdParms) { return ExecuteSql(null, SQLString, cmdParms.ToArray()); } public static int ExecuteSql(string SQLString, params OracleParameter[] cmdParms) { return ExecuteSql(null, SQLString, cmdParms); } public static int ExecuteSql(OracleTransaction sqlTrans, string SQLString, List<OracleParameter> cmdParms) { return ExecuteSql(sqlTrans, SQLString, cmdParms.ToArray()); } #endregion //---------单表操作------------------- #region 获取表所有列信息 /// <summary> /// 获取表所有列信息 /// </summary> /// <param name="strTbName">表名</param> /// <returns>COLUMN_NAME,DATA_TYPE,DATA_LENGTH,NULLABLE,constraint_type</returns> public static DataTable getTabelColsInfos(string strTbName) { try { string cacheKey = "TCOLS_" + strTbName; object obj = DataCache.GetCache(cacheKey); DataTable rtn = null; if (obj == null) { //获取表所有列 string strSql = string.Format(@" select T0.COLUMN_NAME,T0.DATA_TYPE,T0.DATA_LENGTH,T0.NULLABLE,to_char(substr(wmsys.wm_concat(T2.constraint_type),0,4000)) constraint_type from user_tab_columns T0 LEFT JOIN user_cons_columns T1 ON T1.column_name =T0.column_name AND T1.table_name=T0.table_name left join user_constraints T2 ON T1.constraint_name =T2.constraint_name AND T1.table_name=T2.table_name AND T1.owner=T2.owner where T0.table_name={0}) group by T0.COLUMN_NAME,T0.DATA_TYPE,T0.DATA_LENGTH,T0.NULLABLE", DBHelper.setVarcharFiled(strTbName.ToUpper().Trim()) ); rtn = QueryTable(strSql); DataCache.SetCache(cacheKey, rtn); } else rtn = (DataTable)obj; return rtn; } catch { return null; } } /// <summary> /// 获取表所有列信息 /// </summary> /// <param name="strTbName">表名</param> /// <returns>所有列名字符串,以逗号分隔</returns> public static string getTabelCols(string strTbName) { try { string cacheKey = "SCOLS_" + strTbName; object obj = DataCache.GetCache(cacheKey); if (obj == null) { //获取表所有列 string strSql = string.Format("select to_char(substr(wmsys.wm_concat(T.column_name),0,4000)) from user_tab_columns T where T.table_name={0}" , DBHelper.setVarcharFiled(strTbName.ToUpper().Trim()) ); obj = OracleDbHelper.GetSingle(strSql); DataCache.SetCache(cacheKey, obj); } return (obj == null ? "" : obj.ToString()); } catch { return ""; } } #endregion #region GetData 获取表或视图数据 private static string getCValue(ConditionType CType, object CValue) { switch (CType) { case ConditionType.num: return DBHelper.setNumFiled(CValue); case ConditionType.date: return DBHelper.setOracleDateTime(CValue); default: return DBHelper.setVarcharFiled(CValue); } } /// <summary> /// 查询数据表或View数据,支持分页 /// </summary> /// <param name="CQuery">查询条件</param> /// <param name="strTbName">表或View名称(不区分大小写)</param> /// <returns>查询结果</returns> public static DataTable getData(List<CSearchCondition> CQuery, string strTbName) { return getData(CQuery, strTbName, "T.*"); } /// <summary> /// 解析查询条件 /// </summary> /// <param name="CQuery">查询条件</param> /// <param name="strTbName">表名</param> /// <returns>查询条件</returns> public static string getCSearchCondition(List<CSearchCondition> CQuery, string strTbName) { int page_size=0, page_no=0; string strOrderBy = ""; return getCSearchCondition(CQuery, strTbName, out page_size, out page_no,out strOrderBy); } /// <summary> /// 解析查询条件 /// </summary> /// <param name="CQuery">查询条件</param> /// <param name="strTbName">表名</param> /// <param name="page_size">分页行数</param> /// <param name="page_no">页码</param> /// <param name="strOrderBy">排序</param> /// <returns>查询条件</returns> public static string getCSearchCondition(List<CSearchCondition> CQuery, string strTbName, out int page_size, out int page_no, out string strOrderBy) { string strCols = getTabelCols(strTbName).ToUpper(); string strWhere = ""; strOrderBy = ""; page_size = 0; page_no = 0;//分页查询 string cKey, cValue = ""; if (CQuery != null) { foreach (CSearchCondition condition in CQuery) { cKey = string.IsNullOrEmpty(condition.Key) ? "" : condition.Key.ToUpper(); if (!string.IsNullOrEmpty(cKey) && Common.inStr(strCols, cKey, ',') && condition.value != null) { if (condition.qCond != queryCondition.exists && condition.qCond != queryCondition.nexists) { cValue = getCValue(condition.type, condition.value); } #region 添加查询条件 switch (condition.qCond) { case queryCondition.neq: strWhere += string.Format(" and T.{0}!={1}", cKey, cValue); break; case queryCondition.eq: strWhere += string.Format(" and T.{0}={1}", cKey, cValue); break; case queryCondition.gt: strWhere += string.Format(" and T.{0}>{1}", cKey, cValue); break; case queryCondition.gte: strWhere += string.Format(" and T.{0}>={1}", cKey, cValue); break; case queryCondition.lt: strWhere += string.Format(" and T.{0}<{1}", cKey, cValue); break; case queryCondition.lte: strWhere += string.Format(" and T.{0}<={1}", cKey, cValue); break; case queryCondition.Like: strWhere += string.Format(" and T.{0} like '%'||{1}||'%'", cKey, cValue); break; case queryCondition.LF_Like: strWhere += string.Format(" and T.{0} like '%'||{1}", cKey, cValue); break; case queryCondition.RT_Like: strWhere += string.Format(" and T.{0} like {1}||'%'", cKey, cValue); break; case queryCondition.IN: strWhere += string.Format(" and T.{0} in( '{1}')", cKey, string.Join("','",cValue.Trim(new char[]{',','\''}).Split(','))); break; case queryCondition.NIN: strWhere += string.Format(" and T.{0} not in( {1})", cKey, cValue); break; case queryCondition.exists: strWhere += string.Format(" and exists({0})", condition.value); break; case queryCondition.nexists: strWhere += string.Format(" and not exists({0})", condition.value); break; default: strWhere += string.Format("T.{0}={1}", cKey, cValue); ; break; } #endregion } else if (string.IsNullOrEmpty(cKey)) { if (!string.IsNullOrEmpty(condition.conditionSql)) { strWhere += condition.conditionSql; } if (condition.comMod != null) { page_no = condition.comMod.PAGE_NO; page_size = condition.comMod.PAGE_SIZE; strOrderBy = string.IsNullOrEmpty(condition.comMod.SORT.Trim()) ? "" : " order by " + condition.comMod.SORT; } } } } return strWhere; } /// <summary> /// 查询数据表或View数据,支持分页 /// </summary> /// <param name="CQuery">查询条件</param> /// <param name="strTbName">表或View名称(不区分大小写)</param> /// <param name="selectFields">查询字段</param> /// <returns>查询结果</returns> public static DataTable getData(List<CSearchCondition> CQuery, string strTbName, string selectFields) { string strSql = ""; try { if (string.IsNullOrEmpty(selectFields)) selectFields = "T.*"; string strOrderBy = ""; int page_size = 0, page_no = 0;//分页查询 string strWhere =" where 1=1 "+ getCSearchCondition(CQuery, strTbName, out page_size, out page_no, out strOrderBy); strSql = "select " + selectFields + " from " + strTbName + " T " + strWhere + strOrderBy; //如果是分页,则返回的table表名为查询条件的总行数 return OracleDbHelper.PagingQuery(strSql, page_size, page_no); } catch (OracleException OExp) { throw new Exception(OExp.Message + "\n SQL is:" + strSql); } } #endregion } #endregion }
apache-2.0
jonbcampos/ngCommon
src/common/directives/validators/bigdecimal.js
2333
/** * Created by jonbcampos on 8/28/14. */ (function () { 'use strict'; /** * @ngdoc directive * @name common.directives.validations.bigdecimal * @element input * @restrict A * @scope * * @description * Validator for big decimal type numbers. * * @example * <doc:example module="demoApp"> * <doc:source> * <form name="form"> * <div> * <input type="text" name="exampleInput" ng-model="exampleInput" bigdecimal></input> * </div> * <p> * <span ng-if="form.exampleInput.$invalid">Invalid</span> * <span ng-if="!form.exampleInput.$invalid">Valid</span> * </p> * <p> * Input Value: {{exampleInput}} * </p> * </form> * </doc:source> * </doc:example> */ var bigDecimalDirective = angular.module('common.directives.validations.bigdecimal', []); bigDecimalDirective.directive('bigdecimal', [function () { return { restrict: "A", require: 'ngModel', link: function (scope, elm, attrs, ctrl) { var DECIMAL_REGEXP = /^\-?\d{0,2}(?:\.\d{1,8})?$/; ctrl.$parsers.unshift(function (viewValue) { if (DECIMAL_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('bigdecimal', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('bigdecimal', false); return undefined; } }); ctrl.$formatters.unshift(function (viewValue) { if (DECIMAL_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('bigdecimal', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('bigdecimal', false); return undefined; } }); } }; }]); })();
apache-2.0
alapierre/altkom_2014_07_22
src/Child.java
1083
/* * Copyright 2014 Adrian Lapierre <adrian@soft-project.pl>. * * 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. */ /** * * @author Adrian Lapierre <adrian@soft-project.pl> */ public class Child extends Parent { public Child() { super(1); System.out.println("konstuktor child"); } @Override public void m1() { System.out.println("in child"); } public void m2() { System.out.println("m2 w Child"); } public void m3(String str) { System.out.println("String str"); } }
apache-2.0
consulo/consulo-scala
src/org/jetbrains/plugins/scala/lang/parser/parsing/expressions/Generator.scala
1059
package org.jetbrains.plugins.scala package lang package parser package parsing package expressions import com.intellij.lang.PsiBuilder import lexer.ScalaTokenTypes import patterns.{Pattern1, Guard} import builder.ScalaPsiBuilder /** * @author Alexander Podkhalyuzin * Date: 06.03.2008 */ /* * Generator ::= Pattern1 '<-' Expr [Guard] */ object Generator { def parse(builder: ScalaPsiBuilder): Boolean = { val genMarker = builder.mark if (builder.getTokenType == ScalaTokenTypes.kVAL) builder.advanceLexer //deprecated if (!Pattern1.parse(builder)) { genMarker.drop return false } builder.getTokenType match { case ScalaTokenTypes.tCHOOSE => { builder.advanceLexer } case _ => { builder error ErrMsg("choose.expected") } } if (!Expr.parse(builder)) builder error ErrMsg("wrong.expression") genMarker.done(ScalaElementTypes.GENERATOR) builder.getTokenType match { case ScalaTokenTypes.kIF => Guard parse builder case _ => {} } return true } }
apache-2.0
zaradai/primes
src/main/java/com/zaradai/primes/PrimeGeneratorSink.java
693
/** * Copyright 2014 Zaradai * * 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 com.zaradai.primes; public interface PrimeGeneratorSink { void onPrime(int primeValue); }
apache-2.0
relution-io/relution-sdk
lib/query/SortOrderComparator.d.ts
1465
import { SortOrder } from './SortOrder'; /** * options of #jsonCompare function. */ export interface JsonCompareOptions { /** * set to explicitly use case-sensitive string matching, evalates to false to use matching * semantics of WebSQL. */ casesensitive?: boolean; } /** * compiled compare function. */ export interface JsonCompareFn<T> { /** * compares objects in a way compatible to Array.sort(). * * @param o1 left operand. * @param o2 right operand. * @return {number} indicating relative ordering of operands. */ (o1: T, o2: T): number; } /** * compiles a JsonCompareFn from a given SortOrder. * * @param json of SortOrder being compiled. * @return {function} a JsonCompareFn function compatible to Array.sort(). */ export declare function jsonCompare<T>(json: string, options?: JsonCompareOptions): JsonCompareFn<T>; /** * compiles a JsonCompareFn from a given SortOrder. * * @param json of SortOrder being compiled. * @return {function} a JsonCompareFn function compatible to Array.sort(). */ export declare function jsonCompare<T>(json: string[], options?: JsonCompareOptions): JsonCompareFn<T>; /** * compiles a JsonCompareFn from a given SortOrder. * * @param sortOrder being compiled. * @return {function} a JsonCompareFn function compatible to Array.sort(). */ export declare function jsonCompare<T>(sortOrder: SortOrder, options?: JsonCompareOptions): JsonCompareFn<T>;
apache-2.0
enyojs/canvas
index.js
27
exports.version = '2.7.0';
apache-2.0
open-adk/OpenADK-java
adk-generator/src/main/java/openadk/generator/FieldType.java
5636
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // package openadk.generator; public class FieldType { private static FieldType FIELD_BOOLEAN = new FieldType( ADKDataType.BOOLEAN ); private static FieldType FIELD_STRING = new FieldType( ADKDataType.STRING ); private static FieldType FIELD_DATE = new FieldType( ADKDataType.DATE ); private static FieldType FIELD_TIME = new FieldType( ADKDataType.TIME ); private static FieldType FIELD_DATETIME = new FieldType( ADKDataType.DATETIME ); private static FieldType FIELD_DURATION = new FieldType( ADKDataType.DURATION ); private static FieldType FIELD_FLOAT = new FieldType( ADKDataType.FLOAT ); private static FieldType FIELD_INT = new FieldType( ADKDataType.INT ); private static FieldType FIELD_UINT = new FieldType( ADKDataType.UINT ); private static FieldType FIELD_LONG = new FieldType( ADKDataType.LONG ); private static FieldType FIELD_ULONG = new FieldType( ADKDataType.ULONG ); private static FieldType FIELD_DECIMAL = new FieldType( ADKDataType.DECIMAL ); private static FieldType FIELD_SIFVERSION = new FieldType( ADKDataType.SIFVERSION ); private ADKDataType fDataType; private String fClassType; private FieldType( ADKDataType valueType ){ fDataType = valueType; } public boolean isComplex(){ return fDataType == ADKDataType.COMPLEX; } public boolean isEnum(){ return fDataType == ADKDataType.ENUM; } public boolean isSimpleType(){ return !( isComplex() || isEnum() ); } public String getClassType() { return fClassType; } public String getEnum() { if( fDataType == ADKDataType.ENUM ){ return fClassType; } return null; } public ADKDataType getDataType() { return fDataType; } public static FieldType getFieldType( String classType ) { if( classType == null || classType.length() == 0 || classType.equalsIgnoreCase( "String" ) || classType.equalsIgnoreCase( "Token" ) || classType.equalsIgnoreCase( "NormalizedString" ) || classType.equalsIgnoreCase( "NCName" ) || classType.equalsIgnoreCase( "IdRefType" ) || classType.equalsIgnoreCase( "AnyUri" ) ){ return FIELD_STRING; } else if( classType.equalsIgnoreCase( "DateTime" ) ){ return FIELD_DATETIME; } else if( classType.equalsIgnoreCase( "Int" ) || classType.equalsIgnoreCase( "PositiveInteger" ) || classType.equalsIgnoreCase( "GYear" ) || classType.equalsIgnoreCase( "GMonth" ) || classType.equalsIgnoreCase( "GDay") ){ return FIELD_INT; } else if( classType.equalsIgnoreCase( "UnsignedInt" ) || classType.equalsIgnoreCase( "NonNegativeInteger" ) || classType.equalsIgnoreCase( "UInt" ) ){ return FIELD_UINT; } else if( classType.equalsIgnoreCase( "Long" ) ){ return FIELD_LONG; } else if( classType.equalsIgnoreCase( "ULong" ) ){ return FIELD_ULONG; }else if( classType.equalsIgnoreCase( "Decimal" ) ){ return FIELD_DECIMAL; }else if( classType.equalsIgnoreCase( "Float" ) ){ return FIELD_FLOAT; } else if( classType.equalsIgnoreCase( "SIFDate" ) || classType.equalsIgnoreCase( "Date" ) ){ return FIELD_DATE; } else if( classType.equalsIgnoreCase( "Boolean" ) || classType.equalsIgnoreCase( "YesNo" ) ){ return FIELD_BOOLEAN; } else if( classType.equalsIgnoreCase( "SIFSimpleTime" )|| classType.equalsIgnoreCase( "Time" ) || classType.equalsIgnoreCase( "SIFTime" ) ){ return FIELD_TIME; }else if( classType.equalsIgnoreCase( "SIFVersion" ) ){ return FIELD_SIFVERSION; }else if( classType.equals( "duration" ) ){ // NOTE: The value "duration" is case sensitive because there is a "Duration" // type in the ADK return FIELD_DURATION; } else { FieldType returnValue = new FieldType( ADKDataType.COMPLEX ); returnValue.fClassType = classType; return returnValue; } } public static FieldType toEnumType( FieldType existingField, String enumName ) throws ParseException { if (enumName.equalsIgnoreCase( "Topics" )) { return FIELD_STRING; } if( existingField.getDataType() == ADKDataType.ENUM ){ if( existingField.getClassType().equals( enumName ) ) { return existingField; } else { throw new ParseException( "Field was already defined as an Enum with a different name: " + existingField.getDataType() + " { ENUM:" + enumName + "}" ); } } else { if( existingField.getDataType() != ADKDataType.STRING ){ throw new ParseException( "Cannot define an enum for a type other than a String. Field:" + existingField.getDataType() + " { ENUM:" + enumName + "}" ); } } // TODO: We could support "YesNo" values as boolean fields, but we need to be able // to format them differently than booleans.... // if( enumName.equals( "YesNo" )){ // return FIELD_BOOLEAN; // } FieldType returnValue = new FieldType( ADKDataType.ENUM ); returnValue.fClassType = enumName; return returnValue; } @Override public boolean equals(Object o) { if( this == o ) { return true; } if ((o != null) && (o.getClass().equals(this.getClass()))) { FieldType compared = (FieldType)o; if( fDataType == ADKDataType.COMPLEX || fDataType == ADKDataType.ENUM ){ return fClassType.equals( compared.fClassType ); } else { return fDataType.equals( compared.fDataType ); } } return false; } @Override public String toString() { if( isComplex() ){ return "Complex Field: " + getClassType(); } else if ( isEnum() ){ return "Enum Field: " + getEnum(); } else { return "Simple Field: " + fDataType; } } }
apache-2.0
cneill/designate
designate/storage/impl_sqlalchemy/tables.py
13173
# Copyright 2012-2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # 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. from sqlalchemy import (Table, MetaData, Column, String, Text, Integer, CHAR, DateTime, Enum, Boolean, Unicode, UniqueConstraint, ForeignKeyConstraint) from oslo_config import cfg from oslo_utils import timeutils from designate import utils from designate.sqlalchemy.types import UUID CONF = cfg.CONF RESOURCE_STATUSES = ['ACTIVE', 'PENDING', 'DELETED', 'ERROR'] RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'SRV', 'TXT', 'SPF', 'NS', 'PTR', 'SSHFP'] TASK_STATUSES = ['ACTIVE', 'PENDING', 'DELETED', 'ERROR', 'COMPLETE'] TSIG_ALGORITHMS = ['hmac-md5', 'hmac-sha1', 'hmac-sha224', 'hmac-sha256', 'hmac-sha384', 'hmac-sha512'] TSIG_SCOPES = ['POOL', 'ZONE'] POOL_PROVISIONERS = ['UNMANAGED'] ACTIONS = ['CREATE', 'DELETE', 'UPDATE', 'NONE'] ZONE_ATTRIBUTE_KEYS = ('master',) ZONE_TYPES = ('PRIMARY', 'SECONDARY',) metadata = MetaData() quotas = Table('quotas', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('tenant_id', String(36), default=None, nullable=True), Column('resource', String(32), nullable=False), Column('hard_limit', Integer(), nullable=False), mysql_engine='InnoDB', mysql_charset='utf8', ) tlds = Table('tlds', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('name', String(255), nullable=False, unique=True), Column('description', Unicode(160), nullable=True), mysql_engine='InnoDB', mysql_charset='utf8', ) domains = Table('domains', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('deleted', CHAR(32), nullable=False, default='0', server_default='0'), Column('deleted_at', DateTime, nullable=True, default=None), Column('tenant_id', String(36), default=None, nullable=True), Column('name', String(255), nullable=False), Column('email', String(255), nullable=False), Column('description', Unicode(160), nullable=True), Column("type", Enum(name='type', *ZONE_TYPES), nullable=False), Column('transferred_at', DateTime, default=None), Column('ttl', Integer, default=CONF.default_ttl, nullable=False), Column('serial', Integer, default=timeutils.utcnow_ts, nullable=False), Column('refresh', Integer, default=CONF.default_soa_refresh, nullable=False), Column('retry', Integer, default=CONF.default_soa_retry, nullable=False), Column('expire', Integer, default=CONF.default_soa_expire, nullable=False), Column('minimum', Integer, default=CONF.default_soa_minimum, nullable=False), Column('status', Enum(name='resource_statuses', *RESOURCE_STATUSES), nullable=False, server_default='PENDING', default='PENDING'), Column('parent_domain_id', UUID, default=None, nullable=True), Column('action', Enum(name='actions', *ACTIONS), default='CREATE', server_default='CREATE', nullable=False), Column('pool_id', UUID, default=None, nullable=True), Column('reverse_name', String(255), nullable=False), UniqueConstraint('name', 'deleted', 'pool_id', name='unique_domain_name'), ForeignKeyConstraint(['parent_domain_id'], ['domains.id'], ondelete='SET NULL'), mysql_engine='InnoDB', mysql_charset='utf8', ) domain_attributes = Table('domain_attributes', metadata, Column('id', UUID(), default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('key', Enum(name='key', *ZONE_ATTRIBUTE_KEYS)), Column('value', String(255), nullable=False), Column('domain_id', UUID(), nullable=False), UniqueConstraint('key', 'value', 'domain_id', name='unique_attributes'), ForeignKeyConstraint(['domain_id'], ['domains.id'], ondelete='CASCADE'), mysql_engine='INNODB', mysql_charset='utf8' ) recordsets = Table('recordsets', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('tenant_id', String(36), default=None, nullable=True), Column('domain_id', UUID, nullable=False), Column('name', String(255), nullable=False), Column('type', Enum(name='record_types', *RECORD_TYPES), nullable=False), Column('ttl', Integer, default=None, nullable=True), Column('description', Unicode(160), nullable=True), Column('reverse_name', String(255), nullable=False, default=''), UniqueConstraint('domain_id', 'name', 'type', name='unique_recordset'), ForeignKeyConstraint(['domain_id'], ['domains.id'], ondelete='CASCADE'), mysql_engine='InnoDB', mysql_charset='utf8', ) records = Table('records', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('tenant_id', String(36), default=None, nullable=True), Column('domain_id', UUID, nullable=False), Column('recordset_id', UUID, nullable=False), Column('data', Text, nullable=False), Column('description', Unicode(160), nullable=True), Column('hash', String(32), nullable=False, unique=True), Column('managed', Boolean, default=False), Column('managed_extra', Unicode(100), default=None, nullable=True), Column('managed_plugin_type', Unicode(50), default=None, nullable=True), Column('managed_plugin_name', Unicode(50), default=None, nullable=True), Column('managed_resource_type', Unicode(50), default=None, nullable=True), Column('managed_resource_region', Unicode(100), default=None, nullable=True), Column('managed_resource_id', UUID, default=None, nullable=True), Column('managed_tenant_id', Unicode(36), default=None, nullable=True), Column('status', Enum(name='resource_statuses', *RESOURCE_STATUSES), server_default='PENDING', default='PENDING', nullable=False), Column('action', Enum(name='actions', *ACTIONS), default='CREATE', server_default='CREATE', nullable=False), Column('serial', Integer(), server_default='1', nullable=False), UniqueConstraint('hash', name='unique_record'), ForeignKeyConstraint(['domain_id'], ['domains.id'], ondelete='CASCADE'), ForeignKeyConstraint(['recordset_id'], ['recordsets.id'], ondelete='CASCADE'), mysql_engine='InnoDB', mysql_charset='utf8', ) tsigkeys = Table('tsigkeys', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('name', String(255), nullable=False, unique=True), Column('algorithm', Enum(name='tsig_algorithms', *TSIG_ALGORITHMS), nullable=False), Column('secret', String(255), nullable=False), Column('scope', Enum(name='tsig_scopes', *TSIG_SCOPES), nullable=False), Column('resource_id', UUID, nullable=False), mysql_engine='InnoDB', mysql_charset='utf8', ) blacklists = Table('blacklists', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('pattern', String(255), nullable=False, unique=True), Column('description', Unicode(160), nullable=True), mysql_engine='InnoDB', mysql_charset='utf8', ) pools = Table('pools', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('version', Integer(), default=1, nullable=False), Column('name', String(50), nullable=False, unique=True), Column('description', Unicode(160), nullable=True), Column('tenant_id', String(36), nullable=True), Column('provisioner', Enum(name='pool_provisioner', *POOL_PROVISIONERS), nullable=False, server_default='UNMANAGED'), UniqueConstraint('name', name='unique_pool_name'), mysql_engine='INNODB', mysql_charset='utf8' ) pool_attributes = Table('pool_attributes', metadata, Column('id', UUID(), default=utils.generate_uuid, primary_key=True), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('version', Integer(), default=1, nullable=False), Column('key', String(255), nullable=False), Column('value', String(255), nullable=False), Column('pool_id', UUID(), nullable=False), ForeignKeyConstraint(['pool_id'], ['pools.id'], ondelete='CASCADE'), mysql_engine='INNODB', mysql_charset='utf8' ) pool_ns_records = Table('pool_ns_records', metadata, Column('id', UUID(), default=utils.generate_uuid, primary_key=True), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('version', Integer(), default=1, nullable=False), Column('pool_id', UUID(), nullable=False), Column('priority', Integer(), nullable=False), Column('hostname', String(255), nullable=False), ForeignKeyConstraint(['pool_id'], ['pools.id'], ondelete='CASCADE'), mysql_engine='INNODB', mysql_charset='utf8') zone_transfer_requests = Table('zone_transfer_requests', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('domain_id', UUID, nullable=False), Column("key", String(255), nullable=False), Column("description", String(255), nullable=False), Column("tenant_id", String(36), default=None, nullable=False), Column("target_tenant_id", String(36), default=None, nullable=True), Column("status", Enum(name='resource_statuses', *TASK_STATUSES), nullable=False, server_default='ACTIVE', default='ACTIVE'), ForeignKeyConstraint(['domain_id'], ['domains.id'], ondelete='CASCADE'), mysql_engine='InnoDB', mysql_charset='utf8', ) zone_transfer_accepts = Table('zone_transfer_accepts', metadata, Column('id', UUID, default=utils.generate_uuid, primary_key=True), Column('version', Integer(), default=1, nullable=False), Column('created_at', DateTime, default=lambda: timeutils.utcnow()), Column('updated_at', DateTime, onupdate=lambda: timeutils.utcnow()), Column('domain_id', UUID, nullable=False), Column('zone_transfer_request_id', UUID, nullable=False), Column("tenant_id", String(36), default=None, nullable=False), Column("status", Enum(name='resource_statuses', *TASK_STATUSES), nullable=False, server_default='ACTIVE', default='ACTIVE'), ForeignKeyConstraint(['domain_id'], ['domains.id'], ondelete='CASCADE'), ForeignKeyConstraint( ['zone_transfer_request_id'], ['zone_transfer_requests.id'], ondelete='CASCADE'), mysql_engine='InnoDB', mysql_charset='utf8', )
apache-2.0
funkyfuture/docker-py
docker/transport/unixconn.py
3840
import six import requests.adapters import socket from six.moves import http_client as httplib from docker.transport.basehttpadapter import BaseHTTPAdapter from .. import constants try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer class UnixHTTPResponse(httplib.HTTPResponse, object): def __init__(self, sock, *args, **kwargs): disable_buffering = kwargs.pop('disable_buffering', False) if six.PY2: # FIXME: We may need to disable buffering on Py3 as well, # but there's no clear way to do it at the moment. See: # https://github.com/docker/docker-py/issues/1799 kwargs['buffering'] = not disable_buffering super(UnixHTTPResponse, self).__init__(sock, *args, **kwargs) class UnixHTTPConnection(httplib.HTTPConnection, object): def __init__(self, base_url, unix_socket, timeout=60): super(UnixHTTPConnection, self).__init__( 'localhost', timeout=timeout ) self.base_url = base_url self.unix_socket = unix_socket self.timeout = timeout self.disable_buffering = False def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.timeout) sock.connect(self.unix_socket) self.sock = sock def putheader(self, header, *values): super(UnixHTTPConnection, self).putheader(header, *values) if header == 'Connection' and 'Upgrade' in values: self.disable_buffering = True def response_class(self, sock, *args, **kwargs): if self.disable_buffering: kwargs['disable_buffering'] = True return UnixHTTPResponse(sock, *args, **kwargs) class UnixHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): def __init__(self, base_url, socket_path, timeout=60, maxsize=10): super(UnixHTTPConnectionPool, self).__init__( 'localhost', timeout=timeout, maxsize=maxsize ) self.base_url = base_url self.socket_path = socket_path self.timeout = timeout def _new_conn(self): return UnixHTTPConnection( self.base_url, self.socket_path, self.timeout ) class UnixHTTPAdapter(BaseHTTPAdapter): __attrs__ = requests.adapters.HTTPAdapter.__attrs__ + ['pools', 'socket_path', 'timeout'] def __init__(self, socket_url, timeout=60, pool_connections=constants.DEFAULT_NUM_POOLS): socket_path = socket_url.replace('http+unix://', '') if not socket_path.startswith('/'): socket_path = '/' + socket_path self.socket_path = socket_path self.timeout = timeout self.pools = RecentlyUsedContainer( pool_connections, dispose_func=lambda p: p.close() ) super(UnixHTTPAdapter, self).__init__() def get_connection(self, url, proxies=None): with self.pools.lock: pool = self.pools.get(url) if pool: return pool pool = UnixHTTPConnectionPool( url, self.socket_path, self.timeout ) self.pools[url] = pool return pool def request_url(self, request, proxies): # The select_proxy utility in requests errors out when the provided URL # doesn't have a hostname, like is the case when using a UNIX socket. # Since proxies are an irrelevant notion in the case of UNIX sockets # anyway, we simply return the path URL directly. # See also: https://github.com/docker/docker-py/issues/811 return request.path_url
apache-2.0
ChetanBhasin/Veracious
app/models/batch/job/MnALS.scala
600
package models.batch.job /** * Created by basso on 07/04/15. * * MineOp job for the ALS operation */ case class MnALS ( ds_train: String, // JSON file, space separated ds_query: String, // JSON file, space separated ranks: Int, // = 10 max_iter: Int, // = 20 id: String = " " ) extends MineOp { def setId(nid: String) = this.copy(id = nid) def logWrite = jobPrintFormat(id, "ALS (Alternating Least Square) mining", Map("training_datSet" -> ds_train, "query" -> ds_query, "ranks" -> ranks.toString, "iterations" -> max_iter.toString)) }
apache-2.0
EonEngine/Eon
Eon/Source/Assets/Assets.cpp
774
#include <SOIL.h> #include <fstream> #include <iostream> #include "Common.h" #include "Assets/Assets.h" namespace eon { namespace assets { const std::string assetsDir("../Assets/"); std::string LoadText(const char *name) { std::string fileName(assetsDir + name); std::ifstream file(fileName.c_str(), std::ios::in); std::string ret; if (file.is_open()) { while (file.good()) { ret += file.get(); } ret.erase(ret.size() - 1); ret += (char)0; } else { return NULL; } file.close(); return ret; } byte *LoadImage(const char *name, int *width, int *height) { std::string fileName(assetsDir + name); return SOIL_load_image(fileName.c_str(), width, height, 0, SOIL_LOAD_RGB); } void UnloadImage(byte *image) { SOIL_free_image_data(image); } } }
apache-2.0
JeevanJames/ConsoleFx
src/ConsoleExtensions/Clr.cs
9042
#region --- License & Copyright Notice --- /* ConsoleFx CLI Library Suite Copyright 2015-2019 Jeevan James 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. */ #endregion using System.Text; namespace ConsoleFx.ConsoleExtensions { /// <summary> /// Structure that represents a foreground and background color. /// </summary> public readonly struct Clr { public static InstanceClr Black => new InstanceClr(CColor.Black, null); public static InstanceClr Blue => new InstanceClr(CColor.Blue, null); public static InstanceClr Cyan => new InstanceClr(CColor.Cyan, null); public static InstanceClr DkBlue => new InstanceClr(CColor.DkBlue, null); public static InstanceClr DkCyan => new InstanceClr(CColor.DkCyan, null); public static InstanceClr DkGray => new InstanceClr(CColor.DkGray, null); public static InstanceClr DkGreen => new InstanceClr(CColor.DkGreen, null); public static InstanceClr DkMagenta => new InstanceClr(CColor.DkMagenta, null); public static InstanceClr DkRed => new InstanceClr(CColor.DkRed, null); public static InstanceClr DkYellow => new InstanceClr(CColor.DkYellow, null); public static InstanceClr Gray => new InstanceClr(CColor.DkGray, null); public static InstanceClr Green => new InstanceClr(CColor.Green, null); public static InstanceClr Magenta => new InstanceClr(CColor.Magenta, null); public static InstanceClr Red => new InstanceClr(CColor.Red, null); public static InstanceClr White => new InstanceClr(CColor.White, null); public static InstanceClr Yellow => new InstanceClr(CColor.Yellow, null); public static InstanceClr Reset => new InstanceClr(CColor.Reset, null); public static InstanceClr BgBlack => new InstanceClr(null, CColor.Black); public static InstanceClr BgBlue => new InstanceClr(null, CColor.Blue); public static InstanceClr BgCyan => new InstanceClr(null, CColor.Cyan); public static InstanceClr BgDkBlue => new InstanceClr(null, CColor.DkBlue); public static InstanceClr BgDkCyan => new InstanceClr(null, CColor.DkCyan); public static InstanceClr BgDkGray => new InstanceClr(null, CColor.DkGray); public static InstanceClr BgDkGreen => new InstanceClr(null, CColor.DkGreen); public static InstanceClr BgDkMagenta => new InstanceClr(null, CColor.DkMagenta); public static InstanceClr BgDkRed => new InstanceClr(null, CColor.DkRed); public static InstanceClr BgDkYellow => new InstanceClr(null, CColor.DkYellow); public static InstanceClr BgGray => new InstanceClr(null, CColor.Gray); public static InstanceClr BgGreen => new InstanceClr(null, CColor.Green); public static InstanceClr BgMagenta => new InstanceClr(null, CColor.Magenta); public static InstanceClr BgRed => new InstanceClr(null, CColor.Red); public static InstanceClr BgWhite => new InstanceClr(null, CColor.White); public static InstanceClr BgYellow => new InstanceClr(null, CColor.Yellow); public static InstanceClr BgReset => new InstanceClr(null, CColor.Reset); } public readonly struct InstanceClr { private readonly CColor?[] _colors; /// <summary> /// Initializes a new instance of the <see cref="InstanceClr"/> struct with the specified /// <paramref name="foregroundColor"/> and <paramref name="backgroundColor"/>. /// </summary> /// <param name="foregroundColor">Optional foreground color.</param> /// <param name="backgroundColor">Optional background color.</param> internal InstanceClr(CColor? foregroundColor, CColor? backgroundColor) { _colors = new CColor?[2] { foregroundColor, backgroundColor }; } /// <summary> /// Initializes a new instance of the <see cref="InstanceClr"/> struct with the specified /// <paramref name="foregroundColor"/> and <paramref name="backgroundColor"/>. /// <para /> /// If either of the colors are not specified, they are initialized from the specified /// <paramref name="clr"/> value. /// </summary> /// <param name="clr"> /// The <see cref="InstanceClr"/> structure to initialize this instance from, if either <paramref name="foregroundColor"/> or <paramref name="backgroundColor"/> are not specified. /// </param> /// <param name="foregroundColor">Optional foreground color.</param> /// <param name="backgroundColor">Optional background color.</param> /// <remarks> /// This constructor can only be called from an <see cref="InstanceClr"/> instance only, /// hence it is private. /// </remarks> private InstanceClr(InstanceClr clr, CColor? foregroundColor, CColor? backgroundColor) { _colors = new CColor?[2] { foregroundColor ?? clr._colors[0], backgroundColor ?? clr._colors[1], }; } public override string ToString() { if (!_colors[0].HasValue && !_colors[1].HasValue) return string.Empty; var sb = new StringBuilder(); if (_colors[0].HasValue) sb.Append(_colors[0].Value.ToString()); if (_colors[1].HasValue) { if (sb.Length > 0) sb.Append("."); sb.Append("Bg").Append(_colors[1].Value.ToString()); } if (sb.Length > 0) sb.Insert(0, "[").Append("]"); return sb.ToString(); } public InstanceClr Black => new InstanceClr(this, CColor.Black, null); public InstanceClr Blue => new InstanceClr(this, CColor.Blue, null); public InstanceClr Cyan => new InstanceClr(this, CColor.Cyan, null); public InstanceClr DkBlue => new InstanceClr(this, CColor.DkBlue, null); public InstanceClr DkCyan => new InstanceClr(this, CColor.DkCyan, null); public InstanceClr DkGray => new InstanceClr(this, CColor.DkGray, null); public InstanceClr DkGreen => new InstanceClr(this, CColor.DkGreen, null); public InstanceClr DkMagenta => new InstanceClr(this, CColor.DkMagenta, null); public InstanceClr DkRed => new InstanceClr(this, CColor.DkRed, null); public InstanceClr DkYellow => new InstanceClr(this, CColor.DkYellow, null); public InstanceClr Gray => new InstanceClr(this, CColor.DkGray, null); public InstanceClr Green => new InstanceClr(this, CColor.Green, null); public InstanceClr Magenta => new InstanceClr(this, CColor.Magenta, null); public InstanceClr Red => new InstanceClr(this, CColor.Red, null); public InstanceClr White => new InstanceClr(this, CColor.White, null); public InstanceClr Yellow => new InstanceClr(this, CColor.Yellow, null); public InstanceClr Reset => new InstanceClr(this, CColor.Reset, null); public InstanceClr BgBlack => new InstanceClr(this, null, CColor.Black); public InstanceClr BgBlue => new InstanceClr(this, null, CColor.Blue); public InstanceClr BgCyan => new InstanceClr(this, null, CColor.Cyan); public InstanceClr BgDkBlue => new InstanceClr(this, null, CColor.DkBlue); public InstanceClr BgDkCyan => new InstanceClr(this, null, CColor.DkCyan); public InstanceClr BgDkGray => new InstanceClr(this, null, CColor.DkGray); public InstanceClr BgDkGreen => new InstanceClr(this, null, CColor.DkGreen); public InstanceClr BgDkMagenta => new InstanceClr(this, null, CColor.DkMagenta); public InstanceClr BgDkRed => new InstanceClr(this, null, CColor.DkRed); public InstanceClr BgDkYellow => new InstanceClr(this, null, CColor.DkYellow); public InstanceClr BgGray => new InstanceClr(this, null, CColor.Gray); public InstanceClr BgGreen => new InstanceClr(this, null, CColor.Green); public InstanceClr BgMagenta => new InstanceClr(this, null, CColor.Magenta); public InstanceClr BgRed => new InstanceClr(this, null, CColor.Red); public InstanceClr BgWhite => new InstanceClr(this, null, CColor.White); public InstanceClr BgYellow => new InstanceClr(this, null, CColor.Yellow); public InstanceClr BgReset => new InstanceClr(this, null, CColor.Reset); } }
apache-2.0
linkedin/pinot
pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/segment_generation_and_push/SegmentGenerationAndPushTaskExecutorFactory.java
1630
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.pinot.plugin.minion.tasks.segment_generation_and_push; import org.apache.pinot.core.common.MinionConstants; import org.apache.pinot.minion.executor.MinionTaskZkMetadataManager; import org.apache.pinot.minion.executor.PinotTaskExecutor; import org.apache.pinot.minion.executor.PinotTaskExecutorFactory; import org.apache.pinot.spi.annotations.minion.TaskExecutorFactory; @TaskExecutorFactory public class SegmentGenerationAndPushTaskExecutorFactory implements PinotTaskExecutorFactory { @Override public void init(MinionTaskZkMetadataManager zkMetadataManager) { } @Override public String getTaskType() { return MinionConstants.SegmentGenerationAndPushTask.TASK_TYPE; } @Override public PinotTaskExecutor create() { return new SegmentGenerationAndPushTaskExecutor(); } }
apache-2.0
googleapis/python-pubsublite
google/cloud/pubsublite/internal/fast_serialize.py
247
""" A fast serialization method for lists of integers. """ from typing import List def dump(data: List[int]) -> str: return ",".join(str(x) for x in data) def load(source: str) -> List[int]: return [int(x) for x in source.split(",")]
apache-2.0