code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Lluis Parcerisa <lparcerisa@cttc.cat> * Modified by: * Danilo Abrignani <danilo.abrignani@unibo.it> (Carrier Aggregation - GSoC 2015) * Biljana Bojovic <biljana.bojovic@cttc.es> (Carrier Aggregation) */ #include "ns3/log.h" #include "ns3/lte-rrc-header.h" #include <stdio.h> #include <sstream> #define MAX_DRB 11 // According to section 6.4 3GPP TS 36.331 #define MAX_EARFCN 262143 #define MAX_RAT_CAPABILITIES 8 #define MAX_SI_MESSAGE 32 #define MAX_SIB 32 #define MAX_REPORT_CONFIG_ID 32 #define MAX_OBJECT_ID 32 #define MAX_MEAS_ID 32 #define MAX_CELL_MEAS 32 #define MAX_CELL_REPORT 8 #define MAX_SCELL_REPORT 5 #define MAX_SCELL_CONF 5 namespace ns3 { NS_LOG_COMPONENT_DEFINE ("RrcHeader"); //////////////////// RrcAsn1Header class /////////////////////////////// RrcAsn1Header::RrcAsn1Header () { } TypeId RrcAsn1Header::GetTypeId (void) { static TypeId tid = TypeId ("ns3::RrcAsn1Header") .SetParent<Header> () .SetGroupName("Lte") ; return tid; } TypeId RrcAsn1Header::GetInstanceTypeId (void) const { return GetTypeId (); } int RrcAsn1Header::GetMessageType () { return m_messageType; } void RrcAsn1Header::SerializeDrbToAddModList (std::list<LteRrcSap::DrbToAddMod> drbToAddModList) const { // Serialize DRB-ToAddModList sequence-of SerializeSequenceOf (drbToAddModList.size (),MAX_DRB,1); // Serialize the elements in the sequence-of list std::list<LteRrcSap::DrbToAddMod>::iterator it = drbToAddModList.begin (); for (; it != drbToAddModList.end (); it++) { // Serialize DRB-ToAddMod sequence // 5 otional fields. Extension marker is present. std::bitset<5> drbToAddModListOptionalFieldsPresent = std::bitset<5> (); drbToAddModListOptionalFieldsPresent.set (4,1); // eps-BearerIdentity present drbToAddModListOptionalFieldsPresent.set (3,0); // pdcp-Config not present drbToAddModListOptionalFieldsPresent.set (2,1); // rlc-Config present drbToAddModListOptionalFieldsPresent.set (1,1); // logicalChannelIdentity present drbToAddModListOptionalFieldsPresent.set (0,1); // logicalChannelConfig present SerializeSequence (drbToAddModListOptionalFieldsPresent,true); // Serialize eps-BearerIdentity::=INTEGER (0..15) SerializeInteger (it->epsBearerIdentity,0,15); // Serialize drb-Identity ::= INTEGER (1..32) SerializeInteger (it->drbIdentity,1,32); switch (it->rlcConfig.choice) { case LteRrcSap::RlcConfig::UM_BI_DIRECTIONAL: // Serialize rlc-Config choice SerializeChoice (4,1,true); // Serialize UL-UM-RLC SerializeSequence (std::bitset<0> (),false); SerializeEnum (2,0); // sn-FieldLength // Serialize DL-UM-RLC SerializeSequence (std::bitset<0> (),false); SerializeEnum (2,0); // sn-FieldLength SerializeEnum (32,0); // t-Reordering break; case LteRrcSap::RlcConfig::UM_UNI_DIRECTIONAL_UL: // Serialize rlc-Config choice SerializeChoice (4,2,true); // Serialize UL-UM-RLC SerializeSequence (std::bitset<0> (),false); SerializeEnum (2,0); // sn-FieldLength break; case LteRrcSap::RlcConfig::UM_UNI_DIRECTIONAL_DL: // Serialize rlc-Config choice SerializeChoice (4,3,true); // Serialize DL-UM-RLC SerializeSequence (std::bitset<0> (),false); SerializeEnum (2,0); // sn-FieldLength SerializeEnum (32,0); // t-Reordering break; case LteRrcSap::RlcConfig::AM: default: // Serialize rlc-Config choice SerializeChoice (4,0,true); // Serialize UL-AM-RLC SerializeSequence (std::bitset<0> (),false); SerializeEnum (64,0); // t-PollRetransmit SerializeEnum (8,0); // pollPDU SerializeEnum (16,0); // pollByte SerializeEnum (8,0); // maxRetxThreshold // Serialize DL-AM-RLC SerializeSequence (std::bitset<0> (),false); SerializeEnum (32,0); // t-Reordering SerializeEnum (64,0); // t-StatusProhibit break; } // Serialize logicalChannelIdentity ::=INTEGER (3..10) SerializeInteger (it->logicalChannelIdentity,3,10); // Serialize logicalChannelConfig SerializeLogicalChannelConfig (it->logicalChannelConfig); } } void RrcAsn1Header::SerializeSrbToAddModList (std::list<LteRrcSap::SrbToAddMod> srbToAddModList) const { // Serialize SRB-ToAddModList ::= SEQUENCE (SIZE (1..2)) OF SRB-ToAddMod SerializeSequenceOf (srbToAddModList.size (),2,1); // Serialize the elements in the sequence-of list std::list<LteRrcSap::SrbToAddMod>::iterator it = srbToAddModList.begin (); for (; it != srbToAddModList.end (); it++) { // Serialize SRB-ToAddMod sequence // 2 otional fields. Extension marker is present. std::bitset<2> srbToAddModListOptionalFieldsPresent = std::bitset<2> (); srbToAddModListOptionalFieldsPresent.set (1,0); // rlc-Config not present srbToAddModListOptionalFieldsPresent.set (0,1); // logicalChannelConfig present SerializeSequence (srbToAddModListOptionalFieldsPresent,true); // Serialize srb-Identity ::= INTEGER (1..2) SerializeInteger (it->srbIdentity,1,2); // Serialize logicalChannelConfig choice // 2 options, selected option 0 (var "explicitValue", of type LogicalChannelConfig) SerializeChoice (2,0,false); // Serialize LogicalChannelConfig SerializeLogicalChannelConfig (it->logicalChannelConfig); } } void RrcAsn1Header::SerializeLogicalChannelConfig (LteRrcSap::LogicalChannelConfig logicalChannelConfig) const { // Serialize LogicalChannelConfig sequence // 1 optional field (ul-SpecificParameters), which is present. Extension marker present. SerializeSequence (std::bitset<1> (1),true); // Serialize ul-SpecificParameters sequence // 1 optional field (logicalChannelGroup), which is present. No extension marker. SerializeSequence (std::bitset<1> (1),false); // Serialize priority ::= INTEGER (1..16) SerializeInteger (logicalChannelConfig.priority,1,16); // Serialize prioritisedBitRate int prioritizedBitRate; switch (logicalChannelConfig.prioritizedBitRateKbps) { case 0: prioritizedBitRate = 0; break; case 8: prioritizedBitRate = 1; break; case 16: prioritizedBitRate = 2; break; case 32: prioritizedBitRate = 3; break; case 64: prioritizedBitRate = 4; break; case 128: prioritizedBitRate = 5; break; case 256: prioritizedBitRate = 6; break; default: prioritizedBitRate = 7; // Infinity } SerializeEnum (16,prioritizedBitRate); // Serialize bucketSizeDuration int bucketSizeDuration; switch (logicalChannelConfig.bucketSizeDurationMs) { case 50: bucketSizeDuration = 0; break; case 100: bucketSizeDuration = 1; break; case 150: bucketSizeDuration = 2; break; case 300: bucketSizeDuration = 3; break; case 500: bucketSizeDuration = 4; break; case 1000: bucketSizeDuration = 5; break; default: bucketSizeDuration = 5; } SerializeEnum (8,bucketSizeDuration); // Serialize logicalChannelGroup ::= INTEGER (0..3) SerializeInteger (logicalChannelConfig.logicalChannelGroup,0,3); } void RrcAsn1Header::SerializePhysicalConfigDedicated (LteRrcSap::PhysicalConfigDedicated physicalConfigDedicated) const { // Serialize PhysicalConfigDedicated Sequence std::bitset<10> optionalFieldsPhysicalConfigDedicated; optionalFieldsPhysicalConfigDedicated.set (9,physicalConfigDedicated.havePdschConfigDedicated); // pdsch-ConfigDedicated optionalFieldsPhysicalConfigDedicated.set (8,0); // pucch-ConfigDedicated not present optionalFieldsPhysicalConfigDedicated.set (7,0); // pusch-ConfigDedicated not present optionalFieldsPhysicalConfigDedicated.set (6,0); // uplinkPowerControlDedicated not present optionalFieldsPhysicalConfigDedicated.set (5,0); // tpc-PDCCH-ConfigPUCCH not present optionalFieldsPhysicalConfigDedicated.set (4,0); // tpc-PDCCH-ConfigPUSCH not present optionalFieldsPhysicalConfigDedicated.set (3,0); // cqi-ReportConfig not present optionalFieldsPhysicalConfigDedicated.set (2,physicalConfigDedicated.haveSoundingRsUlConfigDedicated); // soundingRS-UL-ConfigDedicated optionalFieldsPhysicalConfigDedicated.set (1,physicalConfigDedicated.haveAntennaInfoDedicated); // antennaInfo optionalFieldsPhysicalConfigDedicated.set (0,0); // schedulingRequestConfig not present SerializeSequence (optionalFieldsPhysicalConfigDedicated,true); if (physicalConfigDedicated.havePdschConfigDedicated) { // Serialize Pdsch-ConfigDedicated Sequence: // 0 optional / default fields, no extension marker. SerializeSequence (std::bitset<0> (),false); // Serialize p-a // Assuming the value in the struct is the enum index SerializeEnum (8,physicalConfigDedicated.pdschConfigDedicated.pa); // Serialize release SerializeNull (); } if (physicalConfigDedicated.haveSoundingRsUlConfigDedicated) { // Serialize SoundingRS-UL-ConfigDedicated choice: switch (physicalConfigDedicated.soundingRsUlConfigDedicated.type) { case LteRrcSap::SoundingRsUlConfigDedicated::RESET: SerializeChoice (2,0,false); SerializeNull (); break; case LteRrcSap::SoundingRsUlConfigDedicated::SETUP: default: // 2 options, selected: 1 (setup) SerializeChoice (2,1,false); // Serialize setup sequence // 0 optional / default fields, no extension marker. SerializeSequence (std::bitset<0> (),false); // Serialize srs-Bandwidth SerializeEnum (4,physicalConfigDedicated.soundingRsUlConfigDedicated.srsBandwidth); // Serialize srs-HoppingBandwidth SerializeEnum (4,0); // Serialize freqDomainPosition SerializeInteger (0,0,23); // Serialize duration SerializeBoolean (false); // Serialize srs-ConfigIndex SerializeInteger (physicalConfigDedicated.soundingRsUlConfigDedicated.srsConfigIndex,0,1023); // Serialize transmissionComb SerializeInteger (0,0,1); // Serialize cyclicShift SerializeEnum (8,0); break; } } if (physicalConfigDedicated.haveAntennaInfoDedicated) { // Serialize antennaInfo choice // 2 options. Selected: 0 ("explicitValue" of type "AntennaInfoDedicated") SerializeChoice (2,0,false); // Serialize AntennaInfoDedicated sequence // 1 optional parameter, not present. No extension marker. SerializeSequence (std::bitset<1> (0),false); // Serialize transmissionMode // Assuming the value in the struct is the enum index SerializeEnum (8,physicalConfigDedicated.antennaInfo.transmissionMode); // Serialize ue-TransmitAntennaSelection choice SerializeChoice (2,0,false); // Serialize release SerializeNull (); } } void RrcAsn1Header::SerializeRadioResourceConfigDedicated (LteRrcSap::RadioResourceConfigDedicated radioResourceConfigDedicated) const { bool isSrbToAddModListPresent = !radioResourceConfigDedicated.srbToAddModList.empty (); bool isDrbToAddModListPresent = !radioResourceConfigDedicated.drbToAddModList.empty (); bool isDrbToReleaseListPresent = !radioResourceConfigDedicated.drbToReleaseList.empty (); // 6 optional fields. Extension marker is present. std::bitset<6> optionalFieldsPresent = std::bitset<6> (); optionalFieldsPresent.set (5,isSrbToAddModListPresent); // srb-ToAddModList present optionalFieldsPresent.set (4,isDrbToAddModListPresent); // drb-ToAddModList present optionalFieldsPresent.set (3,isDrbToReleaseListPresent); // drb-ToReleaseList present optionalFieldsPresent.set (2,0); // mac-MainConfig not present optionalFieldsPresent.set (1,0); // sps-Config not present optionalFieldsPresent.set (0,(radioResourceConfigDedicated.havePhysicalConfigDedicated) ? 1 : 0); SerializeSequence (optionalFieldsPresent,true); // Serialize srbToAddModList if (isSrbToAddModListPresent) { SerializeSrbToAddModList (radioResourceConfigDedicated.srbToAddModList); } // Serialize drbToAddModList if (isDrbToAddModListPresent) { SerializeDrbToAddModList (radioResourceConfigDedicated.drbToAddModList); } // Serialize drbToReleaseList if (isDrbToReleaseListPresent) { SerializeSequenceOf (radioResourceConfigDedicated.drbToReleaseList.size (),MAX_DRB,1); std::list<uint8_t>::iterator it = radioResourceConfigDedicated.drbToReleaseList.begin (); for (; it != radioResourceConfigDedicated.drbToReleaseList.end (); it++) { // DRB-Identity ::= INTEGER (1..32) SerializeInteger (*it,1,32); } } if (radioResourceConfigDedicated.havePhysicalConfigDedicated) { SerializePhysicalConfigDedicated (radioResourceConfigDedicated.physicalConfigDedicated); } } void RrcAsn1Header::SerializeSystemInformationBlockType1 (LteRrcSap::SystemInformationBlockType1 systemInformationBlockType1) const { // 3 optional fields, no extension marker. std::bitset<3> sysInfoBlk1Opts; sysInfoBlk1Opts.set (2,0); // p-Max absent sysInfoBlk1Opts.set (1,0); // tdd-Config absent sysInfoBlk1Opts.set (0,0); // nonCriticalExtension absent SerializeSequence (sysInfoBlk1Opts,false); // Serialize cellAccessRelatedInfo // 1 optional field (csgIdentity) which is present, no extension marker. SerializeSequence (std::bitset<1> (1),false); // Serialize plmn-IdentityList SerializeSequenceOf (1,6,1); // PLMN-IdentityInfo SerializeSequence (std::bitset<0> (),false); SerializePlmnIdentity (systemInformationBlockType1.cellAccessRelatedInfo.plmnIdentityInfo.plmnIdentity); // Serialize trackingAreaCode SerializeBitstring (std::bitset<16> (0)); // Serialize cellIdentity SerializeBitstring (std::bitset<28> (systemInformationBlockType1.cellAccessRelatedInfo.cellIdentity)); // Serialize cellBarred SerializeEnum (2,0); // Serialize intraFreqReselection SerializeEnum (2,0); // Serialize csg-Indication SerializeBoolean (systemInformationBlockType1.cellAccessRelatedInfo.csgIndication); // Serialize csg-Identity SerializeBitstring (std::bitset<27> (systemInformationBlockType1.cellAccessRelatedInfo.csgIdentity)); // Serialize cellSelectionInfo SerializeSequence (std::bitset<1> (0),false); // Serialize q-RxLevMin SerializeInteger (-50,-70,-22); // Serialize freqBandIndicator SerializeInteger (1,1,64); // Serialize schedulingInfoList SerializeSequenceOf (1,MAX_SI_MESSAGE,1); // SchedulingInfo SerializeSequence (std::bitset<0> (),false); // si-Periodicity SerializeEnum (7,0); // sib-MappingInfo SerializeSequenceOf (0,MAX_SIB - 1,0); // Serialize si-WindowLength SerializeEnum (7,0); // Serialize systemInfoValueTag SerializeInteger (0,0,31); } void RrcAsn1Header::SerializeRadioResourceConfigCommon (LteRrcSap::RadioResourceConfigCommon radioResourceConfigCommon) const { // 9 optional fields. Extension marker yes. std::bitset<9> rrCfgCmmOpts; rrCfgCmmOpts.set (8,1); // rach-ConfigCommon is present rrCfgCmmOpts.set (7,0); // pdsch-ConfigCommon not present rrCfgCmmOpts.set (6,0); // phich-Config not present rrCfgCmmOpts.set (5,0); // pucch-ConfigCommon not present rrCfgCmmOpts.set (4,0); // soundingRS-UL-ConfigCommon not present rrCfgCmmOpts.set (3,0); // uplinkPowerControlCommon not present rrCfgCmmOpts.set (2,0); // antennaInfoCommon not present rrCfgCmmOpts.set (1,0); // p-Max not present rrCfgCmmOpts.set (0,0); // tdd-Config not present SerializeSequence (rrCfgCmmOpts,true); if (rrCfgCmmOpts[8]) { // Serialize RACH-ConfigCommon SerializeRachConfigCommon (radioResourceConfigCommon.rachConfigCommon); } // Serialize PRACH-Config // 1 optional, 0 extension marker. SerializeSequence (std::bitset<1> (0),false); // Serialize PRACH-Config rootSequenceIndex SerializeInteger (0,0,1023); // Serialize PUSCH-ConfigCommon SerializeSequence (std::bitset<0> (),false); // Serialize pusch-ConfigBasic SerializeSequence (std::bitset<0> (),false); SerializeInteger (1,1,4); SerializeEnum (2,0); SerializeInteger (0,0,98); SerializeBoolean (false); // Serialize UL-ReferenceSignalsPUSCH SerializeSequence (std::bitset<0> (),false); SerializeBoolean (false); SerializeInteger (0,0,29); SerializeBoolean (false); SerializeInteger (4,0,7); // Serialize UL-CyclicPrefixLength SerializeEnum (2,0); } void RrcAsn1Header::SerializeRadioResourceConfigCommonSib (LteRrcSap::RadioResourceConfigCommonSib radioResourceConfigCommonSib) const { SerializeSequence (std::bitset<0> (0),true); // rach-ConfigCommon SerializeRachConfigCommon (radioResourceConfigCommonSib.rachConfigCommon); // bcch-Config SerializeSequence (std::bitset<0> (0),false); SerializeEnum (4,0); // modificationPeriodCoeff // pcch-Config SerializeSequence (std::bitset<0> (0),false); SerializeEnum (4,0); // defaultPagingCycle SerializeEnum (8,0); // nB // prach-Config SerializeSequence (std::bitset<1> (0),false); SerializeInteger (0,0,1023); // rootSequenceIndex // pdsch-ConfigCommon SerializeSequence (std::bitset<0> (0),false); SerializeInteger (0,-60,50); // referenceSignalPower SerializeInteger (0,0,3); // p-b // pusch-ConfigCommon SerializeSequence (std::bitset<0> (0),false); SerializeSequence (std::bitset<0> (0),false); // pusch-ConfigBasic SerializeInteger (1,1,4); // n-SB SerializeEnum (2,0); // hoppingMode SerializeInteger (0,0,98); // pusch-HoppingOffset SerializeBoolean (false); // enable64QAM SerializeSequence (std::bitset<0> (0),false); // UL-ReferenceSignalsPUSCH SerializeBoolean (false); // groupHoppingEnabled SerializeInteger (0,0,29); // groupAssignmentPUSCH SerializeBoolean (false); // sequenceHoppingEnabled SerializeInteger (0,0,7); // cyclicShift // pucch-ConfigCommon SerializeSequence (std::bitset<0> (0),false); SerializeEnum (3,0); // deltaPUCCH-Shift SerializeInteger (0,0,98); // nRB-CQI SerializeInteger (0,0,7); // nCS-AN SerializeInteger (0,0,2047); // n1PUCCH-AN // soundingRS-UL-ConfigCommon SerializeChoice (2,0,false); SerializeNull (); // release // uplinkPowerControlCommon SerializeSequence (std::bitset<0> (0),false); SerializeInteger (0,-126,24); // p0-NominalPUSCH SerializeEnum (8,0); // alpha SerializeInteger (-50,-127,-96); // p0-NominalPUCCH SerializeSequence (std::bitset<0> (0),false); // deltaFList-PUCCH SerializeEnum (3,0); // deltaF-PUCCH-Format1 SerializeEnum (3,0); // deltaF-PUCCH-Format1b SerializeEnum (4,0); // deltaF-PUCCH-Format2 SerializeEnum (3,0); // deltaF-PUCCH-Format2a SerializeEnum (3,0); // deltaF-PUCCH-Format2b SerializeInteger (0,-1,6); // ul-CyclicPrefixLength SerializeEnum (2,0); } void RrcAsn1Header::SerializeSystemInformationBlockType2 (LteRrcSap::SystemInformationBlockType2 systemInformationBlockType2) const { SerializeSequence (std::bitset<2> (0),true); // RadioResourceConfigCommonSib SerializeRadioResourceConfigCommonSib (systemInformationBlockType2.radioResourceConfigCommon); // ue-TimersAndConstants SerializeSequence (std::bitset<0> (0),true); SerializeEnum (8,0); // t300 SerializeEnum (8,0); // t301 SerializeEnum (7,0); // t310 SerializeEnum (8,0); // n310 SerializeEnum (7,0); // t311 SerializeEnum (8,0); // n311 // freqInfo SerializeSequence (std::bitset<2> (3),false); SerializeInteger ((int) systemInformationBlockType2.freqInfo.ulCarrierFreq, 0, MAX_EARFCN); switch (systemInformationBlockType2.freqInfo.ulBandwidth) { case 6: SerializeEnum (6,0); break; case 15: SerializeEnum (6,1); break; case 25: SerializeEnum (6,2); break; case 50: SerializeEnum (6,3); break; case 75: SerializeEnum (6,4); break; case 100: SerializeEnum (6,5); break; default: SerializeEnum (6,0); } SerializeInteger (29,1,32); // additionalSpectrumEmission // timeAlignmentTimerCommon SerializeEnum (8,0); } void RrcAsn1Header::SerializeMeasResults (LteRrcSap::MeasResults measResults) const { // Watchdog: if list has 0 elements, set boolean to false if (measResults.measResultListEutra.empty ()) { measResults.haveMeasResultNeighCells = false; } std::bitset<4> measResultOptional; measResultOptional.set (3, measResults.haveScellsMeas); measResultOptional.set (2, false); //LocationInfo-r10 measResultOptional.set (1, false); // MeasResultForECID-r9 measResultOptional.set (0, measResults.haveMeasResultNeighCells); SerializeSequence(measResultOptional,true); // Serialize measId SerializeInteger (measResults.measId,1,MAX_MEAS_ID); // Serialize measResultServCell sequence SerializeSequence (std::bitset<0> (0),false); // Serialize rsrpResult SerializeInteger (measResults.rsrpResult,0,97); // Serialize rsrqResult SerializeInteger (measResults.rsrqResult,0,34); if (measResults.haveMeasResultNeighCells) { // Serialize Choice = 0 (MeasResultListEUTRA) SerializeChoice (4,0,false); // Serialize measResultNeighCells SerializeSequenceOf (measResults.measResultListEutra.size (),MAX_CELL_REPORT,1); // serialize MeasResultEutra elements in the list std::list<LteRrcSap::MeasResultEutra>::iterator it; for (it = measResults.measResultListEutra.begin (); it != measResults.measResultListEutra.end (); it++) { SerializeSequence (std::bitset<1> (it->haveCgiInfo),false); // Serialize PhysCellId SerializeInteger (it->physCellId, 0, 503); // Serialize CgiInfo if (it->haveCgiInfo) { SerializeSequence (std::bitset<1> (it->cgiInfo.plmnIdentityList.size ()),false); // Serialize cellGlobalId SerializeSequence (std::bitset<0> (0),false); SerializePlmnIdentity (it->cgiInfo.plmnIdentity); SerializeBitstring (std::bitset<28> (it->cgiInfo.cellIdentity)); // Serialize trackingAreaCode SerializeBitstring (std::bitset<16> (it->cgiInfo.trackingAreaCode)); // Serialize plmn-IdentityList if (!it->cgiInfo.plmnIdentityList.empty ()) { SerializeSequenceOf (it->cgiInfo.plmnIdentityList.size (),5,1); std::list<uint32_t>::iterator it2; for (it2 = it->cgiInfo.plmnIdentityList.begin (); it2 != it->cgiInfo.plmnIdentityList.end (); it2++) { SerializePlmnIdentity (*it2); } } } // Serialize measResult std::bitset<2> measResultFieldsPresent; measResultFieldsPresent[1] = it->haveRsrpResult; measResultFieldsPresent[0] = it->haveRsrqResult; SerializeSequence (measResultFieldsPresent,true); if (it->haveRsrpResult) { SerializeInteger (it->rsrpResult,0,97); } if (it->haveRsrqResult) { SerializeInteger (it->rsrqResult,0,34); } } } if (measResults.haveScellsMeas) { // Serialize measResultNeighCells SerializeSequenceOf (measResults.measScellResultList.measResultScell.size (),MAX_SCELL_REPORT,1); // serialize MeasResultServFreqList-r10 elements in the list std::list<LteRrcSap::MeasResultScell>::iterator it; for (it = measResults.measScellResultList.measResultScell.begin (); it != measResults.measScellResultList.measResultScell.end (); it++) { // Serialize measId SerializeInteger (it->servFreqId,0,MAX_MEAS_ID); // ToDo: change with FreqId, currently is the componentCarrierId // Serialize MeasResultServFreqList std::bitset<2> measResultScellPresent; measResultScellPresent[0] = measResults.measScellResultList.haveMeasurementResultsServingSCells; measResultScellPresent[1] = measResults.measScellResultList.haveMeasurementResultsNeighCell; // Not implemented SerializeSequence (measResultScellPresent,true); // Serialize measResult std::bitset<2> measResultScellFieldsPresent; measResultScellFieldsPresent[1] = it->haveRsrpResult; measResultScellFieldsPresent[0] = it->haveRsrqResult; SerializeSequence (measResultScellFieldsPresent,true); if (it->haveRsrpResult) { SerializeInteger (it->rsrpResult,0,97); } if (it->haveRsrqResult) { SerializeInteger (it->rsrqResult,0,34); } } } } void RrcAsn1Header::SerializePlmnIdentity (uint32_t plmnId) const { // plmn-Identity sequence, mcc is optional, no extension marker SerializeSequence (std::bitset<1> (0), false); // Serialize mnc int nDig = (plmnId > 99) ? 3 : 2; SerializeSequenceOf (nDig,3,2); for (int i = nDig - 1; i >= 0; i--) { int n = floor (plmnId / pow (10,i)); SerializeInteger (n,0,9); plmnId -= n * pow (10,i); } // cellReservedForOperatorUse SerializeEnum (2,0); } void RrcAsn1Header::SerializeRachConfigCommon (LteRrcSap::RachConfigCommon rachConfigCommon) const { // rach-ConfigCommon SerializeSequence (std::bitset<0> (0),true); // preambleInfo SerializeSequence (std::bitset<1> (0),false); // numberOfRA-Preambles switch (rachConfigCommon.preambleInfo.numberOfRaPreambles) { case 4: SerializeEnum (16,0); break; case 8: SerializeEnum (16,1); break; case 12: SerializeEnum (16,2); break; case 16: SerializeEnum (16,3); break; case 20: SerializeEnum (16,4); break; case 24: SerializeEnum (16,5); break; case 28: SerializeEnum (16,6); break; case 32: SerializeEnum (16,7); break; case 36: SerializeEnum (16,8); break; case 40: SerializeEnum (16,9); break; case 44: SerializeEnum (16,10); break; case 48: SerializeEnum (16,11); break; case 52: SerializeEnum (16,12); break; case 56: SerializeEnum (16,13); break; case 60: SerializeEnum (16,14); break; case 64: SerializeEnum (16,15); break; default: SerializeEnum (16,0); } SerializeSequence (std::bitset<0> (0),false); // powerRampingParameters SerializeEnum (4,0); // powerRampingStep SerializeEnum (16,0); // preambleInitialReceivedTargetPower SerializeSequence (std::bitset<0> (0),false); // ra-SupervisionInfo // preambleTransMax switch (rachConfigCommon.raSupervisionInfo.preambleTransMax) { case 3: SerializeEnum (11,0); break; case 4: SerializeEnum (11,1); break; case 5: SerializeEnum (11,2); break; case 6: SerializeEnum (11,3); break; case 7: SerializeEnum (11,4); break; case 8: SerializeEnum (11,5); break; case 10: SerializeEnum (11,6); break; case 20: SerializeEnum (11,7); break; case 50: SerializeEnum (11,8); break; case 100: SerializeEnum (11,9); break; case 200: SerializeEnum (11,10); break; default: SerializeEnum (11,0); } // ra-ResponseWindowSize switch (rachConfigCommon.raSupervisionInfo.raResponseWindowSize) { case 2: SerializeEnum (8,0); break; case 3: SerializeEnum (8,1); break; case 4: SerializeEnum (8,2); break; case 5: SerializeEnum (8,3); break; case 6: SerializeEnum (8,4); break; case 7: SerializeEnum (8,5); break; case 8: SerializeEnum (8,6); break; case 10: SerializeEnum (8,7); break; default: SerializeEnum (8,0); } SerializeEnum (8,0); // mac-ContentionResolutionTimer SerializeInteger (1,1,8); // maxHARQ-Msg3Tx } void RrcAsn1Header::SerializeQoffsetRange (int8_t qOffsetRange) const { switch (qOffsetRange) { case -24: SerializeEnum (31,0); break; case -22: SerializeEnum (31,1); break; case -20: SerializeEnum (31,2); break; case -18: SerializeEnum (31,3); break; case -16: SerializeEnum (31,4); break; case -14: SerializeEnum (31,5); break; case -12: SerializeEnum (31,6); break; case -10: SerializeEnum (31,7); break; case -8: SerializeEnum (31,8); break; case -6: SerializeEnum (31,9); break; case -5: SerializeEnum (31,10); break; case -4: SerializeEnum (31,11); break; case -3: SerializeEnum (31,12); break; case -2: SerializeEnum (31,13); break; case -1: SerializeEnum (31,14); break; case 0: SerializeEnum (31,15); break; case 1: SerializeEnum (31,16); break; case 2: SerializeEnum (31,17); break; case 3: SerializeEnum (31,18); break; case 4: SerializeEnum (31,19); break; case 5: SerializeEnum (31,20); break; case 6: SerializeEnum (31,21); break; case 8: SerializeEnum (31,22); break; case 10: SerializeEnum (31,23); break; case 12: SerializeEnum (31,24); break; case 14: SerializeEnum (31,25); break; case 16: SerializeEnum (31,26); break; case 18: SerializeEnum (31,27); break; case 20: SerializeEnum (31,28); break; case 22: SerializeEnum (31,29); break; case 24: SerializeEnum (31,30); break; default: SerializeEnum (31,15); } } void RrcAsn1Header::SerializeThresholdEutra (LteRrcSap::ThresholdEutra thresholdEutra) const { switch (thresholdEutra.choice) { case LteRrcSap::ThresholdEutra::THRESHOLD_RSRP: SerializeChoice (2,0,false); SerializeInteger (thresholdEutra.range, 0, 97); break; case LteRrcSap::ThresholdEutra::THRESHOLD_RSRQ: default: SerializeChoice (2,1,false); SerializeInteger (thresholdEutra.range, 0, 34); } } void RrcAsn1Header::SerializeMeasConfig (LteRrcSap::MeasConfig measConfig) const { // Serialize MeasConfig sequence // 11 optional fields, extension marker present std::bitset<11> measConfigOptional; measConfigOptional.set (10, !measConfig.measObjectToRemoveList.empty () ); measConfigOptional.set (9, !measConfig.measObjectToAddModList.empty () ); measConfigOptional.set (8, !measConfig.reportConfigToRemoveList.empty () ); measConfigOptional.set (7, !measConfig.reportConfigToAddModList.empty () ); measConfigOptional.set (6, !measConfig.measIdToRemoveList.empty () ); measConfigOptional.set (5, !measConfig.measIdToAddModList.empty () ); measConfigOptional.set (4, measConfig.haveQuantityConfig ); measConfigOptional.set (3, measConfig.haveMeasGapConfig ); measConfigOptional.set (2, measConfig.haveSmeasure ); measConfigOptional.set (1, false ); // preRegistrationInfoHRPD measConfigOptional.set (0, measConfig.haveSpeedStatePars ); SerializeSequence (measConfigOptional,true); if (!measConfig.measObjectToRemoveList.empty ()) { SerializeSequenceOf (measConfig.measObjectToRemoveList.size (),MAX_OBJECT_ID,1); for (std::list<uint8_t>::iterator it = measConfig.measObjectToRemoveList.begin (); it != measConfig.measObjectToRemoveList.end (); it++) { SerializeInteger (*it, 1, MAX_OBJECT_ID); } } if (!measConfig.measObjectToAddModList.empty ()) { SerializeSequenceOf (measConfig.measObjectToAddModList.size (),MAX_OBJECT_ID,1); for (std::list<LteRrcSap::MeasObjectToAddMod>::iterator it = measConfig.measObjectToAddModList.begin (); it != measConfig.measObjectToAddModList.end (); it++) { SerializeSequence (std::bitset<0> (), false); SerializeInteger (it->measObjectId, 1, MAX_OBJECT_ID); SerializeChoice (4, 0, true); // Select MeasObjectEUTRA // Serialize measObjectEutra std::bitset<5> measObjOpts; measObjOpts.set (4,!it->measObjectEutra.cellsToRemoveList.empty () ); measObjOpts.set (3,!it->measObjectEutra.cellsToAddModList.empty () ); measObjOpts.set (2,!it->measObjectEutra.blackCellsToRemoveList.empty () ); measObjOpts.set (1,!it->measObjectEutra.blackCellsToAddModList.empty () ); measObjOpts.set (0,it->measObjectEutra.haveCellForWhichToReportCGI); SerializeSequence (measObjOpts, true); // Serialize carrierFreq SerializeInteger (it->measObjectEutra.carrierFreq, 0, MAX_EARFCN); // Serialize allowedMeasBandwidth switch (it->measObjectEutra.allowedMeasBandwidth) { case 6: SerializeEnum (6,0); break; case 15: SerializeEnum (6,1); break; case 25: SerializeEnum (6,2); break; case 50: SerializeEnum (6,3); break; case 75: SerializeEnum (6,4); break; case 100: SerializeEnum (6,5); break; default: SerializeEnum (6,0); } SerializeBoolean (it->measObjectEutra.presenceAntennaPort1); SerializeBitstring (std::bitset<2> (it->measObjectEutra.neighCellConfig)); SerializeQoffsetRange (it->measObjectEutra.offsetFreq); if (!it->measObjectEutra.cellsToRemoveList.empty ()) { SerializeSequenceOf (it->measObjectEutra.cellsToRemoveList.size (),MAX_CELL_MEAS,1); for (std::list<uint8_t>::iterator it2 = it->measObjectEutra.cellsToRemoveList.begin (); it2 != it->measObjectEutra.cellsToRemoveList.end (); it2++) { SerializeInteger (*it2, 1, MAX_CELL_MEAS); } } if (!it->measObjectEutra.cellsToAddModList.empty ()) { SerializeSequenceOf (it->measObjectEutra.cellsToAddModList.size (), MAX_CELL_MEAS, 1); for (std::list<LteRrcSap::CellsToAddMod>::iterator it2 = it->measObjectEutra.cellsToAddModList.begin (); it2 != it->measObjectEutra.cellsToAddModList.end (); it2++) { SerializeSequence (std::bitset<0> (), false); // Serialize cellIndex SerializeInteger (it2->cellIndex, 1, MAX_CELL_MEAS); // Serialize PhysCellId SerializeInteger (it2->physCellId,0,503); // Serialize cellIndividualOffset SerializeQoffsetRange (it2->cellIndividualOffset); } } if (!it->measObjectEutra.blackCellsToRemoveList.empty () ) { SerializeSequenceOf (it->measObjectEutra.blackCellsToRemoveList.size (),MAX_CELL_MEAS,1); for (std::list<uint8_t>::iterator it2 = it->measObjectEutra.blackCellsToRemoveList.begin (); it2 != it->measObjectEutra.blackCellsToRemoveList.end (); it2++) { SerializeInteger (*it2, 1, MAX_CELL_MEAS); } } if (!it->measObjectEutra.blackCellsToAddModList.empty () ) { SerializeSequenceOf (it->measObjectEutra.blackCellsToAddModList.size (), MAX_CELL_MEAS, 1); for (std::list<LteRrcSap::BlackCellsToAddMod>::iterator it2 = it->measObjectEutra.blackCellsToAddModList.begin (); it2 != it->measObjectEutra.blackCellsToAddModList.end (); it2++) { SerializeSequence (std::bitset<0> (),false); SerializeInteger (it2->cellIndex, 1, MAX_CELL_MEAS); // Serialize PhysCellIdRange // range optional std::bitset<1> rangePresent = std::bitset<1> (it2->physCellIdRange.haveRange); SerializeSequence (rangePresent,false); SerializeInteger (it2->physCellIdRange.start,0,503); if (it2->physCellIdRange.haveRange) { switch (it2->physCellIdRange.range) { case 4: SerializeEnum (16, 0); break; case 8: SerializeEnum (16, 1); break; case 12: SerializeEnum (16, 2); break; case 16: SerializeEnum (16, 3); break; case 24: SerializeEnum (16, 4); break; case 32: SerializeEnum (16, 5); break; case 48: SerializeEnum (16, 6); break; case 64: SerializeEnum (16, 7); break; case 84: SerializeEnum (16, 8); break; case 96: SerializeEnum (16, 9); break; case 128: SerializeEnum (16, 10); break; case 168: SerializeEnum (16, 11); break; case 252: SerializeEnum (16, 12); break; case 504: SerializeEnum (16, 13); break; default: SerializeEnum (16, 0); } } } } if (it->measObjectEutra.haveCellForWhichToReportCGI) { SerializeInteger (it->measObjectEutra.cellForWhichToReportCGI,0,503); } } } if (!measConfig.reportConfigToRemoveList.empty () ) { SerializeSequenceOf (measConfig.reportConfigToRemoveList.size (),MAX_REPORT_CONFIG_ID,1); for (std::list<uint8_t>::iterator it = measConfig.reportConfigToRemoveList.begin (); it != measConfig.reportConfigToRemoveList.end (); it++) { SerializeInteger (*it, 1,MAX_REPORT_CONFIG_ID); } } if (!measConfig.reportConfigToAddModList.empty () ) { SerializeSequenceOf (measConfig.reportConfigToAddModList.size (),MAX_REPORT_CONFIG_ID,1); for (std::list<LteRrcSap::ReportConfigToAddMod>::iterator it = measConfig.reportConfigToAddModList.begin (); it != measConfig.reportConfigToAddModList.end (); it++) { SerializeSequence (std::bitset<0> (), false); SerializeInteger (it->reportConfigId,1,MAX_REPORT_CONFIG_ID); SerializeChoice (2,0,false); // reportConfigEUTRA // Serialize ReportConfigEUTRA SerializeSequence (std::bitset<0> (), true); switch (it->reportConfigEutra.triggerType) { case LteRrcSap::ReportConfigEutra::PERIODICAL: SerializeChoice (2, 1, false); SerializeSequence (std::bitset<0> (),false); switch (it->reportConfigEutra.purpose) { case LteRrcSap::ReportConfigEutra::REPORT_CGI: SerializeEnum (2,1); break; case LteRrcSap::ReportConfigEutra::REPORT_STRONGEST_CELLS: default: SerializeEnum (2,0); } break; case LteRrcSap::ReportConfigEutra::EVENT: default: SerializeChoice (2, 0, false); SerializeSequence (std::bitset<0> (),false); switch (it->reportConfigEutra.eventId) { case LteRrcSap::ReportConfigEutra::EVENT_A1: SerializeChoice (5, 0, true); SerializeSequence (std::bitset<0> (),false); SerializeThresholdEutra (it->reportConfigEutra.threshold1); break; case LteRrcSap::ReportConfigEutra::EVENT_A2: SerializeChoice (5, 1, true); SerializeSequence (std::bitset<0> (),false); SerializeThresholdEutra (it->reportConfigEutra.threshold1); break; case LteRrcSap::ReportConfigEutra::EVENT_A3: SerializeChoice (5, 2, true); SerializeSequence (std::bitset<0> (),false); SerializeInteger (it->reportConfigEutra.a3Offset,-30,30); SerializeBoolean (it->reportConfigEutra.reportOnLeave); break; case LteRrcSap::ReportConfigEutra::EVENT_A4: SerializeChoice (5, 3, true); SerializeSequence (std::bitset<0> (),false); SerializeThresholdEutra (it->reportConfigEutra.threshold1); break; case LteRrcSap::ReportConfigEutra::EVENT_A5: default: SerializeChoice (5, 4, true); SerializeSequence (std::bitset<0> (),false); SerializeThresholdEutra (it->reportConfigEutra.threshold1); SerializeThresholdEutra (it->reportConfigEutra.threshold2); } SerializeInteger (it->reportConfigEutra.hysteresis, 0, 30); switch (it->reportConfigEutra.timeToTrigger) { case 0: SerializeEnum (16, 0); break; case 40: SerializeEnum (16, 1); break; case 64: SerializeEnum (16, 2); break; case 80: SerializeEnum (16, 3); break; case 100: SerializeEnum (16, 4); break; case 128: SerializeEnum (16, 5); break; case 160: SerializeEnum (16, 6); break; case 256: SerializeEnum (16, 7); break; case 320: SerializeEnum (16, 8); break; case 480: SerializeEnum (16, 9); break; case 512: SerializeEnum (16, 10); break; case 640: SerializeEnum (16, 11); break; case 1024: SerializeEnum (16, 12); break; case 1280: SerializeEnum (16, 13); break; case 2560: SerializeEnum (16, 14); break; case 5120: default: SerializeEnum (16, 15); } } // end trigger type // Serialize triggerQuantity if (it->reportConfigEutra.triggerQuantity == LteRrcSap::ReportConfigEutra::RSRP) { SerializeEnum (2, 0); } else { SerializeEnum (2, 1); } // Serialize reportQuantity if (it->reportConfigEutra.reportQuantity == LteRrcSap::ReportConfigEutra::SAME_AS_TRIGGER_QUANTITY) { SerializeEnum (2, 0); } else { SerializeEnum (2, 1); } // Serialize maxReportCells SerializeInteger (it->reportConfigEutra.maxReportCells, 1, MAX_CELL_REPORT); // Serialize reportInterval switch (it->reportConfigEutra.reportInterval) { case LteRrcSap::ReportConfigEutra::MS120: SerializeEnum (16, 0); break; case LteRrcSap::ReportConfigEutra::MS240: SerializeEnum (16, 1); break; case LteRrcSap::ReportConfigEutra::MS480: SerializeEnum (16, 2); break; case LteRrcSap::ReportConfigEutra::MS640: SerializeEnum (16, 3); break; case LteRrcSap::ReportConfigEutra::MS1024: SerializeEnum (16, 4); break; case LteRrcSap::ReportConfigEutra::MS2048: SerializeEnum (16, 5); break; case LteRrcSap::ReportConfigEutra::MS5120: SerializeEnum (16, 6); break; case LteRrcSap::ReportConfigEutra::MS10240: SerializeEnum (16, 7); break; case LteRrcSap::ReportConfigEutra::MIN1: SerializeEnum (16, 8); break; case LteRrcSap::ReportConfigEutra::MIN6: SerializeEnum (16, 9); break; case LteRrcSap::ReportConfigEutra::MIN12: SerializeEnum (16, 10); break; case LteRrcSap::ReportConfigEutra::MIN30: SerializeEnum (16, 11); break; case LteRrcSap::ReportConfigEutra::MIN60: SerializeEnum (16, 12); break; case LteRrcSap::ReportConfigEutra::SPARE3: SerializeEnum (16, 13); break; case LteRrcSap::ReportConfigEutra::SPARE2: SerializeEnum (16, 14); break; case LteRrcSap::ReportConfigEutra::SPARE1: default: SerializeEnum (16, 15); } // Serialize reportAmount switch (it->reportConfigEutra.reportAmount) { case 1: SerializeEnum (8, 0); break; case 2: SerializeEnum (8, 1); break; case 4: SerializeEnum (8, 2); break; case 8: SerializeEnum (8, 3); break; case 16: SerializeEnum (8, 4); break; case 32: SerializeEnum (8, 5); break; case 64: SerializeEnum (8, 6); break; default: SerializeEnum (8, 7); } } } if (!measConfig.measIdToRemoveList.empty () ) { SerializeSequenceOf (measConfig.measIdToRemoveList.size (), MAX_MEAS_ID, 1); for (std::list<uint8_t>::iterator it = measConfig.measIdToRemoveList.begin (); it != measConfig.measIdToRemoveList.end (); it++) { SerializeInteger (*it, 1, MAX_MEAS_ID); } } if (!measConfig.measIdToAddModList.empty () ) { SerializeSequenceOf ( measConfig.measIdToAddModList.size (), MAX_MEAS_ID, 1); for (std::list<LteRrcSap::MeasIdToAddMod>::iterator it = measConfig.measIdToAddModList.begin (); it != measConfig.measIdToAddModList.end (); it++) { SerializeInteger (it->measId, 1, MAX_MEAS_ID); SerializeInteger (it->measObjectId, 1, MAX_OBJECT_ID); SerializeInteger (it->reportConfigId, 1, MAX_REPORT_CONFIG_ID); } } if (measConfig.haveQuantityConfig ) { // QuantityConfig sequence // 4 optional fields, only first (EUTRA) present. Extension marker yes. std::bitset<4> quantityConfigOpts (0); quantityConfigOpts.set (3,1); SerializeSequence (quantityConfigOpts, true); SerializeSequence (std::bitset<0> (), false); switch (measConfig.quantityConfig.filterCoefficientRSRP) { case 0: SerializeEnum (16, 0); break; case 1: SerializeEnum (16, 1); break; case 2: SerializeEnum (16, 2); break; case 3: SerializeEnum (16, 3); break; case 4: SerializeEnum (16, 4); break; case 5: SerializeEnum (16, 5); break; case 6: SerializeEnum (16, 6); break; case 7: SerializeEnum (16, 7); break; case 8: SerializeEnum (16, 8); break; case 9: SerializeEnum (16, 9); break; case 11: SerializeEnum (16, 10); break; case 13: SerializeEnum (16, 11); break; case 15: SerializeEnum (16, 12); break; case 17: SerializeEnum (16, 13); break; case 19: SerializeEnum (16, 14); break; default: SerializeEnum (16, 4); } switch (measConfig.quantityConfig.filterCoefficientRSRQ) { case 0: SerializeEnum (16, 0); break; case 1: SerializeEnum (16, 1); break; case 2: SerializeEnum (16, 2); break; case 3: SerializeEnum (16, 3); break; case 4: SerializeEnum (16, 4); break; case 5: SerializeEnum (16, 5); break; case 6: SerializeEnum (16, 6); break; case 7: SerializeEnum (16, 7); break; case 8: SerializeEnum (16, 8); break; case 9: SerializeEnum (16, 9); break; case 11: SerializeEnum (16, 10); break; case 13: SerializeEnum (16, 11); break; case 15: SerializeEnum (16, 12); break; case 17: SerializeEnum (16, 13); break; case 19: SerializeEnum (16, 14); break; default: SerializeEnum (16, 4); } } if (measConfig.haveMeasGapConfig ) { switch (measConfig.measGapConfig.type) { case LteRrcSap::MeasGapConfig::RESET: SerializeChoice (2, 0, false); SerializeNull (); break; case LteRrcSap::MeasGapConfig::SETUP: default: SerializeChoice (2, 1, false); SerializeSequence (std::bitset<0> (),false); switch (measConfig.measGapConfig.gapOffsetChoice) { case LteRrcSap::MeasGapConfig::GP0: SerializeChoice (2, 0, true); SerializeInteger (measConfig.measGapConfig.gapOffsetValue, 0, 39); break; case LteRrcSap::MeasGapConfig::GP1: default: SerializeChoice (2, 1, true); SerializeInteger (measConfig.measGapConfig.gapOffsetValue, 0, 79); } } } if (measConfig.haveSmeasure ) { SerializeInteger (measConfig.sMeasure, 0, 97); } // ...Here preRegistrationInfoHRPD would be serialized if (measConfig.haveSpeedStatePars ) { switch (measConfig.speedStatePars.type) { case LteRrcSap::SpeedStatePars::RESET: SerializeChoice (2, 0, false); SerializeNull (); break; case LteRrcSap::SpeedStatePars::SETUP: default: SerializeChoice (2, 1, false); SerializeSequence (std::bitset<0> (), false); switch (measConfig.speedStatePars.mobilityStateParameters.tEvaluation) { case 30: SerializeEnum (8, 0); break; case 60: SerializeEnum (8, 1); break; case 120: SerializeEnum (8, 2); break; case 180: SerializeEnum (8, 3); break; case 240: SerializeEnum (8, 4); break; default: SerializeEnum (8, 5); break; } switch (measConfig.speedStatePars.mobilityStateParameters.tHystNormal) { case 30: SerializeEnum (8, 0); break; case 60: SerializeEnum (8, 1); break; case 120: SerializeEnum (8, 2); break; case 180: SerializeEnum (8, 3); break; case 240: SerializeEnum (8, 4); break; default: SerializeEnum (8, 5); break; } SerializeInteger (measConfig.speedStatePars.mobilityStateParameters.nCellChangeMedium, 1, 16); SerializeInteger (measConfig.speedStatePars.mobilityStateParameters.nCellChangeHigh, 1, 16); SerializeSequence (std::bitset<0> (), false); switch (measConfig.speedStatePars.timeToTriggerSf.sfMedium) { case 25: SerializeEnum (4, 0); break; case 50: SerializeEnum (4, 1); break; case 75: SerializeEnum (4, 2); break; case 100: default: SerializeEnum (4, 3); } switch (measConfig.speedStatePars.timeToTriggerSf.sfHigh) { case 25: SerializeEnum (4, 0); break; case 50: SerializeEnum (4, 1); break; case 75: SerializeEnum (4, 2); break; case 100: default: SerializeEnum (4, 3); } } } } void RrcAsn1Header::SerializeNonCriticalExtensionConfiguration (LteRrcSap::NonCriticalExtensionConfiguration nonCriticalExtension) const { // 3 optional fields. Extension marker not present. std::bitset<3> noncriticalExtension_v1020; noncriticalExtension_v1020.set (1,0); // No sCellToRealeaseList-r10 noncriticalExtension_v1020.set (1,1); // sCellToAddModList-r10 noncriticalExtension_v1020.set (0,0); // No nonCriticalExtension RRCConnectionReconfiguration-v1130-IEs SerializeSequence (noncriticalExtension_v1020,false); if (!nonCriticalExtension.sCellsToAddModList.empty ()) { SerializeSequenceOf (nonCriticalExtension.sCellsToAddModList.size (),MAX_OBJECT_ID,1); for (std::list<LteRrcSap::SCellToAddMod>::iterator it = nonCriticalExtension.sCellsToAddModList.begin (); it != nonCriticalExtension.sCellsToAddModList.end (); it++) { std::bitset<4> sCellToAddMod_r10; sCellToAddMod_r10.set (3,1); // sCellIndex sCellToAddMod_r10.set (2,1); // CellIdentification sCellToAddMod_r10.set (1,1); // RadioResourceConfigCommonSCell sCellToAddMod_r10.set (0,it->haveRadioResourceConfigDedicatedSCell); // No nonCriticalExtension RRC SerializeSequence (sCellToAddMod_r10, false); SerializeInteger (it->sCellIndex,1,MAX_OBJECT_ID); //sCellIndex // Serialize CellIdentification std::bitset<2> cellIdentification_r10; cellIdentification_r10.set(1,1); // phyCellId-r10 cellIdentification_r10.set(0,1); // dl-CarrierFreq-r10 SerializeSequence (cellIdentification_r10, false); SerializeInteger (it->cellIdentification.physCellId,1,MAX_EARFCN); SerializeInteger (it->cellIdentification.dlCarrierFreq,1,MAX_EARFCN); //Serialize RadioResourceConfigCommonSCell SerializeRadioResourceConfigCommonSCell (it->radioResourceConfigCommonSCell); if (it->haveRadioResourceConfigDedicatedSCell) { //Serialize RadioResourceConfigDedicatedSCell SerializeRadioResourceDedicatedSCell (it->radioResourceConfigDedicateSCell); } } } else { // NS_ASSERT_MSG ( this << "NonCriticalExtension.sCellsToAddModList cannot be empty ", false); } } void RrcAsn1Header::SerializeRadioResourceConfigCommonSCell (LteRrcSap::RadioResourceConfigCommonSCell rrccsc) const { // 2 optional fields. Extension marker not present. std::bitset<2> radioResourceConfigCommonSCell_r10; radioResourceConfigCommonSCell_r10.set (1,rrccsc.haveNonUlConfiguration); // NonUlConfiguration radioResourceConfigCommonSCell_r10.set (0,rrccsc.haveUlConfiguration); // UlConfiguration SerializeSequence (radioResourceConfigCommonSCell_r10,false); if (radioResourceConfigCommonSCell_r10[1]) { // 5 optional fields. Extension marker not present. std::bitset<5> nonUlConfiguration_r10; nonUlConfiguration_r10.set (4,1); // Dl- bandwidth --> convert in enum nonUlConfiguration_r10.set (3,1); // AntennaInfoCommon-r10 nonUlConfiguration_r10.set (2,0); // phich-Config-r10 Not Implemented nonUlConfiguration_r10.set (1,1); // pdschConfigCommon nonUlConfiguration_r10.set (0,0); // Tdd-Config-r10 Not Implemented SerializeSequence (nonUlConfiguration_r10,false); SerializeInteger (rrccsc.nonUlConfiguration.dlBandwidth,6,100); std::bitset<1> antennaInfoCommon_r10; antennaInfoCommon_r10.set (0,1); SerializeSequence (antennaInfoCommon_r10,false); SerializeInteger (rrccsc.nonUlConfiguration.antennaInfoCommon.antennaPortsCount,0,65536); std::bitset<2> pdschConfigCommon_r10; pdschConfigCommon_r10.set (1,1); pdschConfigCommon_r10.set (0,1); SerializeSequence (pdschConfigCommon_r10,false); SerializeInteger (rrccsc.nonUlConfiguration.pdschConfigCommon.referenceSignalPower,-60,50); SerializeInteger (rrccsc.nonUlConfiguration.pdschConfigCommon.pb,0,3); } if (radioResourceConfigCommonSCell_r10[0]) { //Serialize Ul Configuration // 7 optional fields. Extension marker present. std::bitset<7> UlConfiguration_r10; UlConfiguration_r10.set (6,1); // ul-Configuration-r10 UlConfiguration_r10.set (5,0); // p-Max-r10 Not Implemented UlConfiguration_r10.set (4,1); // uplinkPowerControlCommonSCell-r10 UlConfiguration_r10.set (3,0); // soundingRS-UL-ConfigCommon-r10 UlConfiguration_r10.set (2,0); // ul-CyclicPrefixLength-r10 UlConfiguration_r10.set (1,1); // prach-ConfigSCell-r10 UlConfiguration_r10.set (0,0); // pusch-ConfigCommon-r10 Not Implemented SerializeSequence (UlConfiguration_r10,true); //Serialize ulFreqInfo std::bitset<3> FreqInfo_r10; FreqInfo_r10.set (2,1); // ulCarrierFreq FreqInfo_r10.set (1,1); // UlBandwidth FreqInfo_r10.set (0,0); // additionalSpectrumEmissionSCell-r10 Not Implemented SerializeSequence (FreqInfo_r10,false); SerializeInteger (rrccsc.ulConfiguration.ulFreqInfo.ulCarrierFreq,0,MAX_EARFCN); SerializeInteger (rrccsc.ulConfiguration.ulFreqInfo.ulBandwidth,6,100); //Serialize UlPowerControllCommonSCell std::bitset<2> UlPowerControlCommonSCell_r10; UlPowerControlCommonSCell_r10.set (1,0); // p0-NominalPUSCH-r10 Not Implemented UlPowerControlCommonSCell_r10.set (0,1); // alpha SerializeSequence (UlPowerControlCommonSCell_r10,false); SerializeInteger (rrccsc.ulConfiguration.ulPowerControlCommonSCell.alpha,0,65536); //Serialize soundingRs-UlConfigCommon //Not Implemented //Serialize PrachConfigSCell std::bitset<1> prachConfigSCell_r10; prachConfigSCell_r10.set(0,1); SerializeSequence(prachConfigSCell_r10,false); SerializeInteger (rrccsc.ulConfiguration.prachConfigSCell.index,0,256); } } void RrcAsn1Header::SerializeRadioResourceDedicatedSCell (LteRrcSap::RadioResourceConfigDedicatedSCell rrcdsc) const { //Serialize RadioResourceConfigDedicatedSCell std::bitset<1> RadioResourceConfigDedicatedSCell_r10; RadioResourceConfigDedicatedSCell_r10.set (0,1); SerializeSequence (RadioResourceConfigDedicatedSCell_r10,false); LteRrcSap::PhysicalConfigDedicatedSCell pcdsc = rrcdsc.physicalConfigDedicatedSCell; SerializePhysicalConfigDedicatedSCell (pcdsc); } void RrcAsn1Header::SerializePhysicalConfigDedicatedSCell (LteRrcSap::PhysicalConfigDedicatedSCell pcdsc) const { std::bitset<2> pcdscOpt; pcdscOpt.set (1,pcdsc.haveNonUlConfiguration); pcdscOpt.set (0,pcdsc.haveUlConfiguration); SerializeSequence (pcdscOpt, true); if (pcdscOpt[1]) { //Serialize NonUl configuration std::bitset<4> nulOpt; nulOpt.set (3,pcdsc.haveAntennaInfoDedicated); nulOpt.set (2,0); // crossCarrierSchedulingConfig-r10 NOT IMplemented nulOpt.set (1,0); // csi-RS-Config-r10 Not Implemented nulOpt.set (0, pcdsc.havePdschConfigDedicated); // pdsch-ConfigDedicated-r10 SerializeSequence (nulOpt,false); if (pcdsc.haveAntennaInfoDedicated) { // Serialize antennaInfo choice // 2 options. Selected: 0 ("explicitValue" of type "AntennaInfoDedicated") SerializeChoice (2,0,false); // Serialize AntennaInfoDedicated sequence // 1 optional parameter, not present. No extension marker. SerializeSequence (std::bitset<1> (0),false); // Serialize transmissionMode // Assuming the value in the struct is the enum index SerializeEnum (8,pcdsc.antennaInfo.transmissionMode); // Serialize ue-TransmitAntennaSelection choice SerializeChoice (2,0,false); // Serialize release SerializeNull (); } if (pcdsc.havePdschConfigDedicated) { // Serialize Pdsch-ConfigDedicated Sequence: // 0 optional / default fields, no extension marker. SerializeSequence (std::bitset<0> (),false); // Serialize p-a // Assuming the value in the struct is the enum index SerializeEnum (8,pcdsc.pdschConfigDedicated.pa); // Serialize release SerializeNull (); } } if (pcdscOpt[0]) { //Serialize Ul Configuration std::bitset<7> ulOpt; ulOpt.set (6, pcdsc.haveAntennaInfoUlDedicated);// antennaInfoUL-r10 ulOpt.set (5,0); // pusch-ConfigDedicatedSCell-r10 not present ulOpt.set (4,0); // uplinkPowerControlDedicatedSCell-r10 not present ulOpt.set (3,0); // cqi-ReportConfigSCell-r10 not present ulOpt.set (2,pcdsc.haveSoundingRsUlConfigDedicated);// soundingRS-UL-ConfigDedicated-r10 ulOpt.set (1,0); // soundingRS-UL-ConfigDedicated-v1020 not present ulOpt.set (0,0); // soundingRS-UL-ConfigDedicatedAperiodic-r10 not present SerializeSequence (ulOpt,false); if (pcdsc.haveAntennaInfoUlDedicated) { // Serialize antennaInfo choice // 2 options. Selected: 0 ("explicitValue" of type "AntennaInfoDedicated") SerializeChoice (2,0,false); // Serialize AntennaInfoDedicated sequence // 1 optional parameter, not present. No extension marker. SerializeSequence (std::bitset<1> (0),false); // Serialize transmissionMode // Assuming the value in the struct is the enum index SerializeEnum (8,pcdsc.antennaInfoUl.transmissionMode); // Serialize ue-TransmitAntennaSelection choice SerializeChoice (2,0,false); // Serialize release SerializeNull (); } if (pcdsc.haveSoundingRsUlConfigDedicated) { // Serialize SoundingRS-UL-ConfigDedicated choice: switch (pcdsc.soundingRsUlConfigDedicated.type) { case LteRrcSap::SoundingRsUlConfigDedicated::RESET: SerializeChoice (2,0,false); SerializeNull (); break; case LteRrcSap::SoundingRsUlConfigDedicated::SETUP: default: // 2 options, selected: 1 (setup) SerializeChoice (2,1,false); // Serialize setup sequence // 0 optional / default fields, no extension marker. SerializeSequence (std::bitset<0> (),false); // Serialize srs-Bandwidth SerializeEnum (4,pcdsc.soundingRsUlConfigDedicated.srsBandwidth); // Serialize srs-HoppingBandwidth SerializeEnum (4,0); // Serialize freqDomainPosition SerializeInteger (0,0,23); // Serialize duration SerializeBoolean (false); // Serialize srs-ConfigIndex SerializeInteger (pcdsc.soundingRsUlConfigDedicated.srsConfigIndex,0,1023); // Serialize transmissionComb SerializeInteger (0,0,1); // Serialize cyclicShift SerializeEnum (8,0); break; } } } } Buffer::Iterator RrcAsn1Header::DeserializeThresholdEutra (LteRrcSap::ThresholdEutra * thresholdEutra, Buffer::Iterator bIterator) { int thresholdEutraChoice, range; bIterator = DeserializeChoice (2, false, &thresholdEutraChoice, bIterator); switch (thresholdEutraChoice) { case 0: thresholdEutra->choice = LteRrcSap::ThresholdEutra::THRESHOLD_RSRP; bIterator = DeserializeInteger (&range, 0, 97, bIterator); thresholdEutra->range = range; break; case 1: default: thresholdEutra->choice = LteRrcSap::ThresholdEutra::THRESHOLD_RSRQ; bIterator = DeserializeInteger (&range, 0, 34, bIterator); thresholdEutra->range = range; } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeQoffsetRange (int8_t * qOffsetRange, Buffer::Iterator bIterator) { int n; bIterator = DeserializeEnum (31, &n, bIterator); switch (n) { case 0: *qOffsetRange = -24; break; case 1: *qOffsetRange = -22; break; case 2: *qOffsetRange = -20; break; case 3: *qOffsetRange = -18; break; case 4: *qOffsetRange = -16; break; case 5: *qOffsetRange = -14; break; case 6: *qOffsetRange = -12; break; case 7: *qOffsetRange = -10; break; case 8: *qOffsetRange = -8; break; case 9: *qOffsetRange = -6; break; case 10: *qOffsetRange = -5; break; case 11: *qOffsetRange = -4; break; case 12: *qOffsetRange = -3; break; case 13: *qOffsetRange = -2; break; case 14: *qOffsetRange = -1; break; case 15: *qOffsetRange = 0; break; case 16: *qOffsetRange = 1; break; case 17: *qOffsetRange = 2; break; case 18: *qOffsetRange = 3; break; case 19: *qOffsetRange = 4; break; case 20: *qOffsetRange = 5; break; case 21: *qOffsetRange = 6; break; case 22: *qOffsetRange = 8; break; case 23: *qOffsetRange = 10; break; case 24: *qOffsetRange = 12; break; case 25: *qOffsetRange = 14; break; case 26: *qOffsetRange = 16; break; case 27: *qOffsetRange = 18; break; case 28: *qOffsetRange = 20; break; case 29: *qOffsetRange = 22; break; case 30: default: *qOffsetRange = 24; } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeRadioResourceConfigDedicated (LteRrcSap::RadioResourceConfigDedicated *radioResourceConfigDedicated, Buffer::Iterator bIterator) { // Deserialize RadioResourceConfigDedicated sequence std::bitset<6> optionalFieldsPresent = std::bitset<6> (); bIterator = DeserializeSequence (&optionalFieldsPresent,true,bIterator); if (optionalFieldsPresent[5]) { // Deserialize srb-ToAddModList bIterator = DeserializeSrbToAddModList (&(radioResourceConfigDedicated->srbToAddModList),bIterator); } if (optionalFieldsPresent[4]) { // Deserialize drb-ToAddModList bIterator = DeserializeDrbToAddModList (&(radioResourceConfigDedicated->drbToAddModList),bIterator); } if (optionalFieldsPresent[3]) { // Deserialize drb-ToReleaseList int n; int val; bIterator = DeserializeSequenceOf (&n,MAX_DRB,1,bIterator); for (int i = 0; i < n; i++) { bIterator = DeserializeInteger (&val,1,32,bIterator); radioResourceConfigDedicated->drbToReleaseList.push_back (val); } } if (optionalFieldsPresent[2]) { // Deserialize mac-MainConfig // ... } if (optionalFieldsPresent[1]) { // Deserialize sps-Config // ... } radioResourceConfigDedicated->havePhysicalConfigDedicated = optionalFieldsPresent[0]; if (optionalFieldsPresent[0]) { // Deserialize physicalConfigDedicated bIterator = DeserializePhysicalConfigDedicated (&radioResourceConfigDedicated->physicalConfigDedicated,bIterator); } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeSrbToAddModList (std::list<LteRrcSap::SrbToAddMod> *srbToAddModList, Buffer::Iterator bIterator) { int numElems; bIterator = DeserializeSequenceOf (&numElems,2,1,bIterator); srbToAddModList->clear (); // Deserialize SRB-ToAddMod elements for (int i = 0; i < numElems; i++) { LteRrcSap::SrbToAddMod srbToAddMod; // Deserialize SRB-ToAddMod sequence // 2 optional fields, extension marker present std::bitset<2> optionalFields; bIterator = DeserializeSequence (&optionalFields,true,bIterator); // Deserialize srbIdentity int n; bIterator = DeserializeInteger (&n,1,2,bIterator); srbToAddMod.srbIdentity = n; if (optionalFields[1]) { // Deserialize rlcConfig choice // ... } if (optionalFields[0]) { // Deserialize logicalChannelConfig choice int sel; bIterator = DeserializeChoice (2,false,&sel,bIterator); // Deserialize logicalChannelConfig defaultValue if (sel == 1) { bIterator = DeserializeNull (bIterator); } // Deserialize logicalChannelConfig explicitValue else if (sel == 0) { bIterator = DeserializeLogicalChannelConfig (&srbToAddMod.logicalChannelConfig,bIterator); } } srbToAddModList->insert (srbToAddModList->end (),srbToAddMod); } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeDrbToAddModList (std::list<LteRrcSap::DrbToAddMod> *drbToAddModList, Buffer::Iterator bIterator) { int n; int val; bIterator = DeserializeSequenceOf (&n,MAX_DRB,1,bIterator); drbToAddModList->clear (); for (int i = 0; i < n; i++) { LteRrcSap::DrbToAddMod drbToAddMod; std::bitset<5> optionalFields; bIterator = DeserializeSequence (&optionalFields,true,bIterator); if (optionalFields[4]) { // Deserialize epsBearerIdentity bIterator = DeserializeInteger (&val,0,15,bIterator); drbToAddMod.epsBearerIdentity = val; } bIterator = DeserializeInteger (&val,1,32,bIterator); drbToAddMod.drbIdentity = val; if (optionalFields[3]) { // Deserialize pdcp-Config // ... } if (optionalFields[2]) { // Deserialize RLC-Config int chosen; bIterator = DeserializeChoice (4,true,&chosen,bIterator); int sel; std::bitset<0> bitset0; switch (chosen) { case 0: drbToAddMod.rlcConfig.choice = LteRrcSap::RlcConfig::AM; // Deserialize UL-AM-RLC bIterator = DeserializeSequence (&bitset0,false, bIterator); bIterator = DeserializeEnum (64,&sel, bIterator); // t-PollRetransmit bIterator = DeserializeEnum (8,&sel, bIterator); // pollPDU bIterator = DeserializeEnum (16,&sel, bIterator); // pollByte bIterator = DeserializeEnum (8,&sel, bIterator); // maxRetxThreshold // Deserialize DL-AM-RLC bIterator = DeserializeSequence (&bitset0,false, bIterator); bIterator = DeserializeEnum (32,&sel, bIterator); // t-Reordering bIterator = DeserializeEnum (64,&sel, bIterator); // t-StatusProhibit break; case 1: drbToAddMod.rlcConfig.choice = LteRrcSap::RlcConfig::UM_BI_DIRECTIONAL; // Deserialize UL-UM-RLC bIterator = DeserializeSequence (&bitset0,false, bIterator); bIterator = DeserializeEnum (2,&sel, bIterator); // sn-FieldLength // Deserialize DL-UM-RLC bIterator = DeserializeSequence (&bitset0,false, bIterator); bIterator = DeserializeEnum (2,&sel, bIterator); // sn-FieldLength bIterator = DeserializeEnum (32,&sel, bIterator); // t-Reordering break; case 2: drbToAddMod.rlcConfig.choice = LteRrcSap::RlcConfig::UM_UNI_DIRECTIONAL_UL; // Deserialize UL-UM-RLC bIterator = DeserializeSequence (&bitset0,false, bIterator); bIterator = DeserializeEnum (2,&sel, bIterator); // sn-FieldLength break; case 3: drbToAddMod.rlcConfig.choice = LteRrcSap::RlcConfig::UM_UNI_DIRECTIONAL_DL; // Deserialize DL-UM-RLC bIterator = DeserializeSequence (&bitset0,false, bIterator); bIterator = DeserializeEnum (2,&sel, bIterator); // sn-FieldLength bIterator = DeserializeEnum (32,&sel, bIterator); // t-Reordering break; } } if (optionalFields[1]) { bIterator = DeserializeInteger (&val,3,10,bIterator); drbToAddMod.logicalChannelIdentity = val; } if (optionalFields[0]) { bIterator = DeserializeLogicalChannelConfig (&drbToAddMod.logicalChannelConfig,bIterator); } drbToAddModList->insert (drbToAddModList->end (),drbToAddMod); } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeLogicalChannelConfig (LteRrcSap::LogicalChannelConfig *logicalChannelConfig, Buffer::Iterator bIterator) { int n; // Deserialize LogicalChannelConfig sequence // 1 optional field, extension marker is present. std::bitset<1> bitset1; bIterator = DeserializeSequence (&bitset1,true,bIterator); if (bitset1[0]) { // Deserialize ul-SpecificParameters sequence bIterator = DeserializeSequence (&bitset1,false,bIterator); // Deserialize priority bIterator = DeserializeInteger (&n,1,16,bIterator); logicalChannelConfig->priority = n; // Deserialize prioritisedBitRate bIterator = DeserializeEnum (16,&n,bIterator); uint16_t prioritizedBitRateKbps; switch (n) { case 0: prioritizedBitRateKbps = 0; break; case 1: prioritizedBitRateKbps = 8; break; case 2: prioritizedBitRateKbps = 16; break; case 3: prioritizedBitRateKbps = 32; break; case 4: prioritizedBitRateKbps = 64; break; case 5: prioritizedBitRateKbps = 128; break; case 6: prioritizedBitRateKbps = 256; break; case 7: prioritizedBitRateKbps = 10000; break; default: prioritizedBitRateKbps = 10000; } logicalChannelConfig->prioritizedBitRateKbps = prioritizedBitRateKbps; // Deserialize bucketSizeDuration bIterator = DeserializeEnum (8,&n,bIterator); uint16_t bucketSizeDurationMs; switch (n) { case 0: bucketSizeDurationMs = 50; break; case 1: bucketSizeDurationMs = 100; break; case 2: bucketSizeDurationMs = 150; break; case 3: bucketSizeDurationMs = 300; break; case 4: bucketSizeDurationMs = 500; break; case 5: bucketSizeDurationMs = 1000; break; default: bucketSizeDurationMs = 1000; } logicalChannelConfig->bucketSizeDurationMs = bucketSizeDurationMs; if (bitset1[0]) { // Deserialize logicalChannelGroup bIterator = DeserializeInteger (&n,0,3,bIterator); logicalChannelConfig->logicalChannelGroup = n; } } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializePhysicalConfigDedicated (LteRrcSap::PhysicalConfigDedicated *physicalConfigDedicated, Buffer::Iterator bIterator) { std::bitset<10> optionalFieldPresent; bIterator = DeserializeSequence (&optionalFieldPresent,true,bIterator); physicalConfigDedicated->havePdschConfigDedicated = optionalFieldPresent[9]; if (optionalFieldPresent[9]) { // Deserialize pdsch-ConfigDedicated std::bitset<0> bitset0; bIterator = DeserializeSequence (&bitset0,false,bIterator); int slct; // Deserialize p-a bIterator = DeserializeEnum (8,&slct,bIterator); physicalConfigDedicated->pdschConfigDedicated.pa = slct; bIterator = DeserializeNull (bIterator); } if (optionalFieldPresent[8]) { // Deserialize pucch-ConfigDedicated // ... } if (optionalFieldPresent[7]) { // Deserialize pusch-ConfigDedicated // ... } if (optionalFieldPresent[6]) { // Deserialize uplinkPowerControlDedicated // ... } if (optionalFieldPresent[5]) { // Deserialize tpc-PDCCH-ConfigPUCCH // ... } if (optionalFieldPresent[4]) { // Deserialize tpc-PDCCH-ConfigPUSCH // ... } if (optionalFieldPresent[3]) { // Deserialize cqi-ReportConfig // ... } physicalConfigDedicated->haveSoundingRsUlConfigDedicated = optionalFieldPresent[2]; if (optionalFieldPresent[2]) { // Deserialize soundingRS-UL-ConfigDedicated int sel; bIterator = DeserializeChoice (2,false,&sel,bIterator); if (sel == 0) { physicalConfigDedicated->soundingRsUlConfigDedicated.type = LteRrcSap::SoundingRsUlConfigDedicated::RESET; bIterator = DeserializeNull (bIterator); } else if (sel == 1) { physicalConfigDedicated->soundingRsUlConfigDedicated.type = LteRrcSap::SoundingRsUlConfigDedicated::SETUP; std::bitset<0> bitset0; bIterator = DeserializeSequence (&bitset0,false,bIterator); int slct; // Deserialize srs-Bandwidth bIterator = DeserializeEnum (4,&slct,bIterator); physicalConfigDedicated->soundingRsUlConfigDedicated.srsBandwidth = slct; // Deserialize srs-HoppingBandwidth bIterator = DeserializeEnum (4,&slct,bIterator); // Deserialize freqDomainPosition bIterator = DeserializeInteger (&slct,0,23,bIterator); // Deserialize duration bool duration; bIterator = DeserializeBoolean (&duration,bIterator); // Deserialize srs-ConfigIndex bIterator = DeserializeInteger (&slct,0,1023,bIterator); physicalConfigDedicated->soundingRsUlConfigDedicated.srsConfigIndex = slct; // Deserialize transmissionComb bIterator = DeserializeInteger (&slct,0,1,bIterator); // Deserialize cyclicShift bIterator = DeserializeEnum (8,&slct,bIterator); } } physicalConfigDedicated->haveAntennaInfoDedicated = optionalFieldPresent[1]; if (optionalFieldPresent[1]) { // Deserialize antennaInfo int sel; bIterator = DeserializeChoice (2,false,&sel,bIterator); if (sel == 1) { bIterator = DeserializeNull (bIterator); } else if (sel == 0) { std::bitset<1> codebookSubsetRestrictionPresent; bIterator = DeserializeSequence (&codebookSubsetRestrictionPresent,false,bIterator); int txmode; bIterator = DeserializeEnum (8,&txmode,bIterator); physicalConfigDedicated->antennaInfo.transmissionMode = txmode; if (codebookSubsetRestrictionPresent[0]) { // Deserialize codebookSubsetRestriction // ... } int txantennaselchosen; bIterator = DeserializeChoice (2,false,&txantennaselchosen,bIterator); if (txantennaselchosen == 0) { // Deserialize ue-TransmitAntennaSelection release bIterator = DeserializeNull (bIterator); } else if (txantennaselchosen == 1) { // Deserialize ue-TransmitAntennaSelection setup // ... } } } if (optionalFieldPresent[0]) { // Deserialize schedulingRequestConfig // ... } return bIterator; } void RrcAsn1Header::Print (std::ostream &os) const { NS_LOG_FUNCTION (this << &os); NS_FATAL_ERROR ("RrcAsn1Header Print() function must also specify LteRrcSap::RadioResourceConfigDedicated as a second argument"); } Buffer::Iterator RrcAsn1Header::DeserializeNonCriticalExtensionConfig (LteRrcSap::NonCriticalExtensionConfiguration *nonCriticalExtension, Buffer::Iterator bIterator) { NS_LOG_FUNCTION (this); std::bitset<2> nonCriticalExtension_v890; bIterator = DeserializeSequence (&nonCriticalExtension_v890, false,bIterator); if (nonCriticalExtension_v890[0]) { // Continue to analyze future Release optional fields std::bitset<3> nonCriticalExtension_v920; bIterator = DeserializeSequence (&nonCriticalExtension_v920, false, bIterator); if (nonCriticalExtension_v920[0]) { // Continue to deserialize futere Release optional fields std::bitset<3> nonCriticalExtension_v1020; bIterator = DeserializeSequence (&nonCriticalExtension_v1020, false, bIterator); int numElems; bIterator = DeserializeSequenceOf (&numElems,MAX_OBJECT_ID,1,bIterator); nonCriticalExtension->sCellsToAddModList.clear (); // Deserialize SCellToAddMod for (int i = 0; i < numElems; i++) { std::bitset<4> sCellToAddMod_r10; bIterator = DeserializeSequence (&sCellToAddMod_r10, false, bIterator); LteRrcSap::SCellToAddMod sctam; // Deserialize sCellIndex int n; bIterator = DeserializeInteger (&n,1,MAX_OBJECT_ID,bIterator); sctam.sCellIndex = n; // Deserialize CellIdentification bIterator = DeserializeCellIdentification (&sctam.cellIdentification, bIterator); // Deserialize RadioResourceConfigCommonSCell bIterator = DeserializeRadioResourceConfigCommonSCell (&sctam.radioResourceConfigCommonSCell, bIterator); if (sCellToAddMod_r10[0]) { //Deserialize RadioResourceConfigDedicatedSCell bIterator = DeserializeRadioResourceConfigDedicatedSCell (&sctam.radioResourceConfigDedicateSCell, bIterator); } nonCriticalExtension->sCellsToAddModList.insert (nonCriticalExtension->sCellsToAddModList.end (), sctam); } } } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeCellIdentification (LteRrcSap::CellIdentification *ci, Buffer::Iterator bIterator) { NS_LOG_FUNCTION (this); std::bitset<2> cellIdentification_r10; bIterator = DeserializeSequence (&cellIdentification_r10,false,bIterator); int n1; bIterator = DeserializeInteger (&n1,1,65536,bIterator); ci->physCellId = n1; int n2; bIterator = DeserializeInteger (&n2,1,65536,bIterator); ci->dlCarrierFreq = n2; return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeRadioResourceConfigCommonSCell (LteRrcSap::RadioResourceConfigCommonSCell *rrccsc, Buffer::Iterator bIterator) { NS_LOG_FUNCTION (this); std::bitset<2> radioResourceConfigCommonSCell_r10; bIterator = DeserializeSequence (&radioResourceConfigCommonSCell_r10,false,bIterator); rrccsc->haveNonUlConfiguration = radioResourceConfigCommonSCell_r10[1]; rrccsc->haveUlConfiguration = radioResourceConfigCommonSCell_r10[0]; if (rrccsc->haveNonUlConfiguration) { std::bitset<5> nonUlConfiguration_r10; bIterator = DeserializeSequence (&nonUlConfiguration_r10,false,bIterator); int n; bIterator = DeserializeInteger (&n,6,100,bIterator); rrccsc->nonUlConfiguration.dlBandwidth = n; std::bitset<1> antennaInfoCommon_r10; bIterator = DeserializeSequence (&antennaInfoCommon_r10,false,bIterator); bIterator = DeserializeInteger (&n,0,65536,bIterator); rrccsc->nonUlConfiguration.antennaInfoCommon.antennaPortsCount = n; std::bitset<2> pdschConfigCommon_r10; bIterator = DeserializeSequence (&pdschConfigCommon_r10,false,bIterator); bIterator = DeserializeInteger (&n,-60,50,bIterator); rrccsc->nonUlConfiguration.pdschConfigCommon.referenceSignalPower = n; bIterator = DeserializeInteger (&n,0,3,bIterator); rrccsc->nonUlConfiguration.pdschConfigCommon.pb = n; } if (rrccsc->haveUlConfiguration) { std::bitset<7> UlConfiguration_r10; bIterator = DeserializeSequence (&UlConfiguration_r10,true,bIterator); std::bitset<3> FreqInfo_r10; bIterator = DeserializeSequence (&FreqInfo_r10,false,bIterator); int n; bIterator = DeserializeInteger (&n,0,MAX_EARFCN,bIterator); rrccsc->ulConfiguration.ulFreqInfo.ulCarrierFreq = n; bIterator = DeserializeInteger (&n,6,100,bIterator); rrccsc->ulConfiguration.ulFreqInfo.ulBandwidth = n; std::bitset<2> UlPowerControlCommonSCell_r10; bIterator = DeserializeSequence (&UlPowerControlCommonSCell_r10,false,bIterator); bIterator = DeserializeInteger (&n,0,MAX_EARFCN,bIterator); rrccsc->ulConfiguration.ulPowerControlCommonSCell.alpha = n; std::bitset<1> prachConfigSCell_r10; bIterator = DeserializeSequence (&prachConfigSCell_r10,false,bIterator); bIterator = DeserializeInteger (&n,0,256,bIterator); rrccsc->ulConfiguration.prachConfigSCell.index = n; } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeRadioResourceConfigDedicatedSCell (LteRrcSap::RadioResourceConfigDedicatedSCell *rrcdsc, Buffer::Iterator bIterator) { NS_LOG_FUNCTION (this); std::bitset<1> RadioResourceConfigDedicatedSCell_r10; bIterator = DeserializeSequence (&RadioResourceConfigDedicatedSCell_r10,false,bIterator); DeserializePhysicalConfigDedicatedSCell (&rrcdsc->physicalConfigDedicatedSCell, bIterator); return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializePhysicalConfigDedicatedSCell (LteRrcSap::PhysicalConfigDedicatedSCell *pcdsc, Buffer::Iterator bIterator) { NS_LOG_FUNCTION (this); std::bitset<2> pcdscOpt; bIterator = DeserializeSequence (&pcdscOpt,true,bIterator); pcdsc->haveNonUlConfiguration = pcdscOpt[1]; pcdsc->haveUlConfiguration = pcdscOpt[0]; if (pcdsc->haveNonUlConfiguration) { std::bitset<4> nulOpt; bIterator = DeserializeSequence (&nulOpt,false,bIterator); pcdsc->haveAntennaInfoDedicated = nulOpt[3]; pcdsc->havePdschConfigDedicated = nulOpt[0]; if (pcdsc->haveAntennaInfoDedicated) { // Deserialize antennaInfo int sel; bIterator = DeserializeChoice (2,false,&sel,bIterator); if (sel == 1) { bIterator = DeserializeNull (bIterator); } else if (sel == 0) { std::bitset<1> codebookSubsetRestrictionPresent; bIterator = DeserializeSequence (&codebookSubsetRestrictionPresent,false,bIterator); int txmode; bIterator = DeserializeEnum (8,&txmode,bIterator); pcdsc->antennaInfo.transmissionMode = txmode; if (codebookSubsetRestrictionPresent[0]) { // Deserialize codebookSubsetRestriction // ... } int txantennaselchosen; bIterator = DeserializeChoice (2,false,&txantennaselchosen,bIterator); if (txantennaselchosen == 0) { // Deserialize ue-TransmitAntennaSelection release bIterator = DeserializeNull (bIterator); } else if (txantennaselchosen == 1) { // Deserialize ue-TransmitAntennaSelection setup // ... } } } if (pcdsc->havePdschConfigDedicated) { // Deserialize pdsch-ConfigDedicated std::bitset<0> bitset0; bIterator = DeserializeSequence (&bitset0,false,bIterator); int slct; // Deserialize p-a bIterator = DeserializeEnum (8,&slct,bIterator); pcdsc->pdschConfigDedicated.pa = slct; bIterator = DeserializeNull (bIterator); } } if (pcdsc->haveUlConfiguration) { std::bitset<7> ulOpt; bIterator = DeserializeSequence (&ulOpt,false,bIterator); pcdsc->haveAntennaInfoUlDedicated = ulOpt[6]; pcdsc->haveSoundingRsUlConfigDedicated = ulOpt[2]; if (pcdsc->haveAntennaInfoUlDedicated) { // Deserialize antennaInfo int sel; bIterator = DeserializeChoice (2,false,&sel,bIterator); if (sel == 1) { bIterator = DeserializeNull (bIterator); } else if (sel == 0) { std::bitset<1> codebookSubsetRestrictionPresent; bIterator = DeserializeSequence (&codebookSubsetRestrictionPresent,false,bIterator); int txmode; bIterator = DeserializeEnum (8,&txmode,bIterator); pcdsc->antennaInfo.transmissionMode = txmode; if (codebookSubsetRestrictionPresent[0]) { // Deserialize codebookSubsetRestriction // ... } int txantennaselchosen; bIterator = DeserializeChoice (2,false,&txantennaselchosen,bIterator); if (txantennaselchosen == 0) { // Deserialize ue-TransmitAntennaSelection release bIterator = DeserializeNull (bIterator); } else if (txantennaselchosen == 1) { // Deserialize ue-TransmitAntennaSelection setup // ... } } } if (pcdsc->haveSoundingRsUlConfigDedicated) { // Deserialize soundingRS-UL-ConfigDedicated int sel; bIterator = DeserializeChoice (2,false,&sel,bIterator); if (sel == 0) { pcdsc->soundingRsUlConfigDedicated.type = LteRrcSap::SoundingRsUlConfigDedicated::RESET; bIterator = DeserializeNull (bIterator); } else if (sel == 1) { pcdsc->soundingRsUlConfigDedicated.type = LteRrcSap::SoundingRsUlConfigDedicated::SETUP; std::bitset<0> bitset0; bIterator = DeserializeSequence (&bitset0,false,bIterator); int slct; // Deserialize srs-Bandwidth bIterator = DeserializeEnum (4,&slct,bIterator); pcdsc->soundingRsUlConfigDedicated.srsBandwidth = slct; // Deserialize srs-HoppingBandwidth bIterator = DeserializeEnum (4,&slct,bIterator); // Deserialize freqDomainPosition bIterator = DeserializeInteger (&slct,0,23,bIterator); // Deserialize duration bool duration; bIterator = DeserializeBoolean (&duration,bIterator); // Deserialize srs-ConfigIndex bIterator = DeserializeInteger (&slct,0,1023,bIterator); pcdsc->soundingRsUlConfigDedicated.srsConfigIndex = slct; // Deserialize transmissionComb bIterator = DeserializeInteger (&slct,0,1,bIterator); // Deserialize cyclicShift bIterator = DeserializeEnum (8,&slct,bIterator); } } } return bIterator; } void RrcAsn1Header::Print (std::ostream &os, LteRrcSap::RadioResourceConfigDedicated radioResourceConfigDedicated) const { os << " srbToAddModList: " << std::endl; std::list<LteRrcSap::SrbToAddMod>::iterator it = radioResourceConfigDedicated.srbToAddModList.begin (); for (; it != radioResourceConfigDedicated.srbToAddModList.end (); it++) { os << " srbIdentity: " << (int)it->srbIdentity << std::endl; os << " logicalChannelConfig: " << std::endl; os << " priority: " << (int)it->logicalChannelConfig.priority << std::endl; os << " prioritizedBitRateKbps: " << (int)it->logicalChannelConfig.prioritizedBitRateKbps << std::endl; os << " bucketSizeDurationMs: " << (int)it->logicalChannelConfig.bucketSizeDurationMs << std::endl; os << " logicalChannelGroup: " << (int)it->logicalChannelConfig.logicalChannelGroup << std::endl; } os << std::endl; os << " drbToAddModList: " << std::endl; std::list<LteRrcSap::DrbToAddMod>::iterator it2 = radioResourceConfigDedicated.drbToAddModList.begin (); for (; it2 != radioResourceConfigDedicated.drbToAddModList.end (); it2++) { os << " epsBearerIdentity: " << (int)it2->epsBearerIdentity << std::endl; os << " drbIdentity: " << (int)it2->drbIdentity << std::endl; os << " rlcConfig: " << it2->rlcConfig.choice << std::endl; os << " logicalChannelIdentity: " << (int)it2->logicalChannelIdentity << std::endl; os << " logicalChannelConfig: " << std::endl; os << " priority: " << (int)it2->logicalChannelConfig.priority << std::endl; os << " prioritizedBitRateKbps: " << (int)it2->logicalChannelConfig.prioritizedBitRateKbps << std::endl; os << " bucketSizeDurationMs: " << (int)it2->logicalChannelConfig.bucketSizeDurationMs << std::endl; os << " logicalChannelGroup: " << (int)it2->logicalChannelConfig.logicalChannelGroup << std::endl; } os << std::endl; os << " drbToReleaseList: "; std::list<uint8_t>::iterator it3 = radioResourceConfigDedicated.drbToReleaseList.begin (); for (; it3 != radioResourceConfigDedicated.drbToReleaseList.end (); it3++) { os << (int)*it3 << ", "; } os << std::endl; os << " havePhysicalConfigDedicated: " << radioResourceConfigDedicated.havePhysicalConfigDedicated << std::endl; if (radioResourceConfigDedicated.havePhysicalConfigDedicated) { os << " physicalConfigDedicated: " << std::endl; os << " haveSoundingRsUlConfigDedicated: " << radioResourceConfigDedicated.physicalConfigDedicated.haveSoundingRsUlConfigDedicated << std::endl; if (radioResourceConfigDedicated.physicalConfigDedicated.haveSoundingRsUlConfigDedicated) { os << " soundingRsUlConfigDedicated: " << std::endl; os << " type: " << radioResourceConfigDedicated.physicalConfigDedicated.soundingRsUlConfigDedicated.type << std::endl; os << " srsBandwidth: " << (int)radioResourceConfigDedicated.physicalConfigDedicated.soundingRsUlConfigDedicated.srsBandwidth << std::endl; os << " srsConfigIndex: " << (int)radioResourceConfigDedicated.physicalConfigDedicated.soundingRsUlConfigDedicated.srsConfigIndex << std::endl; } os << " haveAntennaInfoDedicated: " << radioResourceConfigDedicated.physicalConfigDedicated.haveAntennaInfoDedicated << std::endl; if (radioResourceConfigDedicated.physicalConfigDedicated.haveAntennaInfoDedicated) { os << " antennaInfo Tx mode: " << (int)radioResourceConfigDedicated.physicalConfigDedicated.antennaInfo.transmissionMode << std::endl; } } } Buffer::Iterator RrcAsn1Header::DeserializeSystemInformationBlockType1 (LteRrcSap::SystemInformationBlockType1 *systemInformationBlockType1, Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; std::bitset<3> sysInfoBlkT1Opts; bIterator = DeserializeSequence (&sysInfoBlkT1Opts,false,bIterator); // Deserialize cellAccessRelatedInfo std::bitset<1> cellAccessRelatedInfoOpts; bIterator = DeserializeSequence (&cellAccessRelatedInfoOpts,false,bIterator); // Deserialize plmn-IdentityList int numPlmnIdentityInfoElements; bIterator = DeserializeSequenceOf (&numPlmnIdentityInfoElements,6,1,bIterator); for (int i = 0; i < numPlmnIdentityInfoElements; i++) { bIterator = DeserializeSequence (&bitset0,false,bIterator); // plmn-Identity bIterator = DeserializePlmnIdentity (&systemInformationBlockType1->cellAccessRelatedInfo.plmnIdentityInfo.plmnIdentity,bIterator); } // Deserialize trackingAreaCode std::bitset<16> trackingAreaCode; bIterator = DeserializeBitstring (&trackingAreaCode,bIterator); // Deserialize cellIdentity std::bitset<28> cellIdentity; bIterator = DeserializeBitstring (&cellIdentity,bIterator); systemInformationBlockType1->cellAccessRelatedInfo.cellIdentity = cellIdentity.to_ulong (); // Deserialize cellBarred bIterator = DeserializeEnum (2,&n,bIterator); // Deserialize intraFreqReselection bIterator = DeserializeEnum (2,&n,bIterator); // Deserialize csg-Indication bIterator = DeserializeBoolean (&systemInformationBlockType1->cellAccessRelatedInfo.csgIndication,bIterator); if (cellAccessRelatedInfoOpts[0]) { // Deserialize csg-Identity std::bitset<27> csgIdentity; bIterator = DeserializeBitstring (&csgIdentity,bIterator); systemInformationBlockType1->cellAccessRelatedInfo.csgIdentity = csgIdentity.to_ulong (); } // Deserialize cellSelectionInfo std::bitset<1> qRxLevMinOffsetPresent; bIterator = DeserializeSequence (&qRxLevMinOffsetPresent,false,bIterator); bIterator = DeserializeInteger (&n,-70,-22,bIterator); //q-RxLevMin if (qRxLevMinOffsetPresent[0]) { // Deserialize qRxLevMinOffset // ... } if (sysInfoBlkT1Opts[2]) { // Deserialize p-Max // ... } // freqBandIndicator bIterator = DeserializeInteger (&n,1,64,bIterator); // schedulingInfoList int numSchedulingInfo; bIterator = DeserializeSequenceOf (&numSchedulingInfo,MAX_SI_MESSAGE,1,bIterator); for (int i = 0; i < numSchedulingInfo; i++) { bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (7,&n,bIterator); // si-Periodicity int numSibType; bIterator = DeserializeSequenceOf (&numSibType,MAX_SIB - 1,0, bIterator); // sib-MappingInfo for (int j = 0; j < numSibType; j++) { bIterator = DeserializeEnum (16,&n,bIterator); // SIB-Type } } if (sysInfoBlkT1Opts[1]) { // tdd-Config // ... } // si-WindowLength bIterator = DeserializeEnum (7,&n,bIterator); // systemInfoValueTag bIterator = DeserializeInteger (&n,0,31,bIterator); if (sysInfoBlkT1Opts[0]) { // Deserialize nonCriticalExtension // ... } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeSystemInformationBlockType2 (LteRrcSap::SystemInformationBlockType2 *systemInformationBlockType2, Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; std::bitset<2> sysInfoBlkT2Opts; bIterator = DeserializeSequence (&sysInfoBlkT2Opts,true,bIterator); if (sysInfoBlkT2Opts[1]) { // Deserialize ac-BarringInfo // ... } // Deserialize radioResourceConfigCommon bIterator = DeserializeRadioResourceConfigCommonSib (&systemInformationBlockType2->radioResourceConfigCommon, bIterator); // Deserialize ue-TimersAndConstants bIterator = DeserializeSequence (&bitset0,true,bIterator); bIterator = DeserializeEnum (8,&n,bIterator); // t300 bIterator = DeserializeEnum (8,&n,bIterator); // t301 bIterator = DeserializeEnum (7,&n,bIterator); // t310 bIterator = DeserializeEnum (8,&n,bIterator); // n310 bIterator = DeserializeEnum (7,&n,bIterator); // t311 bIterator = DeserializeEnum (8,&n,bIterator); // n311 // Deserialize freqInfo std::bitset<2> freqInfoOpts; bIterator = DeserializeSequence (&freqInfoOpts,false,bIterator); if (freqInfoOpts[1]) { // Deserialize ul-CarrierFreq bIterator = DeserializeInteger (&n, 0, MAX_EARFCN, bIterator); systemInformationBlockType2->freqInfo.ulCarrierFreq = n; } if (freqInfoOpts[0]) { // Deserialize ul-Bandwidth bIterator = DeserializeEnum (6, &n, bIterator); switch (n) { case 0: systemInformationBlockType2->freqInfo.ulBandwidth = 6; break; case 1: systemInformationBlockType2->freqInfo.ulBandwidth = 15; break; case 2: systemInformationBlockType2->freqInfo.ulBandwidth = 25; break; case 3: systemInformationBlockType2->freqInfo.ulBandwidth = 50; break; case 4: systemInformationBlockType2->freqInfo.ulBandwidth = 75; break; case 5: systemInformationBlockType2->freqInfo.ulBandwidth = 100; break; default: systemInformationBlockType2->freqInfo.ulBandwidth = 6; } } // additionalSpectrumEmission bIterator = DeserializeInteger (&n,1,32,bIterator); if (sysInfoBlkT2Opts[0]) { // Deserialize mbsfn-SubframeConfigList // ... } // Deserialize timeAlignmentTimerCommon bIterator = DeserializeEnum (8,&n,bIterator); return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeRadioResourceConfigCommon (LteRrcSap::RadioResourceConfigCommon * radioResourceConfigCommon, Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; std::bitset<9> rrCfgCommOptions; bIterator = DeserializeSequence (&rrCfgCommOptions,true,bIterator); // rach-ConfigCommon if (rrCfgCommOptions[8]) { bIterator = DeserializeRachConfigCommon (&radioResourceConfigCommon->rachConfigCommon, bIterator); } // prach-Config std::bitset<1> prachConfigInfoPresent; bIterator = DeserializeSequence (&prachConfigInfoPresent,false,bIterator); // prach-Config -> rootSequenceIndex bIterator = DeserializeInteger (&n,0,1023,bIterator); // prach-Config -> prach-ConfigInfo if (prachConfigInfoPresent[0]) { // ... } // pdsch-ConfigCommon if (rrCfgCommOptions[7]) { // ... } // pusch-ConfigCommon bIterator = DeserializeSequence (&bitset0,false,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic bIterator = DeserializeSequence (&bitset0,false,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> n-SB bIterator = DeserializeInteger (&n,1,4,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> hoppingMode bIterator = DeserializeEnum (2,&n,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> pusch-HoppingOffset bIterator = DeserializeInteger (&n,0,98,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> enable64QAM bool enable64QAM; bIterator = DeserializeBoolean (&enable64QAM,bIterator); // ul-ReferenceSignalsPUSCH bIterator = DeserializeSequence (&bitset0,false,bIterator); // groupHoppingEnabled bool dummyBool; bIterator = DeserializeBoolean (&dummyBool,bIterator); // groupAssignmentPUSCH bIterator = DeserializeInteger (&n,0,29,bIterator); // sequenceHoppingEnabled bIterator = DeserializeBoolean (&dummyBool,bIterator); // cyclicShift bIterator = DeserializeInteger (&n,0,7,bIterator); // phich-Config if (rrCfgCommOptions[6]) { // ... } // pucch-ConfigCommon if (rrCfgCommOptions[5]) { // ... } // soundingRS-UL-ConfigCommon if (rrCfgCommOptions[4]) { // ... } // uplinkPowerControlCommon if (rrCfgCommOptions[3]) { // ... } // antennaInfoCommon if (rrCfgCommOptions[2]) { // ... } // p-Max if (rrCfgCommOptions[1]) { // ... } // tdd-Config if (rrCfgCommOptions[0]) { // ... } // ul-CyclicPrefixLength bIterator = DeserializeEnum (2,&n,bIterator); return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeRachConfigCommon (LteRrcSap::RachConfigCommon * rachConfigCommon, Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeSequence (&bitset0,true,bIterator); // preambleInfo std::bitset<1> preamblesGroupAConfigPresent; bIterator = DeserializeSequence (&preamblesGroupAConfigPresent,false,bIterator); // numberOfRA-Preambles bIterator = DeserializeEnum (16,&n,bIterator); switch (n) { case 0: rachConfigCommon->preambleInfo.numberOfRaPreambles = 4; break; case 1: rachConfigCommon->preambleInfo.numberOfRaPreambles = 8; break; case 2: rachConfigCommon->preambleInfo.numberOfRaPreambles = 12; break; case 3: rachConfigCommon->preambleInfo.numberOfRaPreambles = 16; break; case 4: rachConfigCommon->preambleInfo.numberOfRaPreambles = 20; break; case 5: rachConfigCommon->preambleInfo.numberOfRaPreambles = 24; break; case 6: rachConfigCommon->preambleInfo.numberOfRaPreambles = 28; break; case 7: rachConfigCommon->preambleInfo.numberOfRaPreambles = 32; break; case 8: rachConfigCommon->preambleInfo.numberOfRaPreambles = 36; break; case 9: rachConfigCommon->preambleInfo.numberOfRaPreambles = 40; break; case 10: rachConfigCommon->preambleInfo.numberOfRaPreambles = 44; break; case 11: rachConfigCommon->preambleInfo.numberOfRaPreambles = 48; break; case 12: rachConfigCommon->preambleInfo.numberOfRaPreambles = 52; break; case 13: rachConfigCommon->preambleInfo.numberOfRaPreambles = 56; break; case 14: rachConfigCommon->preambleInfo.numberOfRaPreambles = 60; break; case 15: rachConfigCommon->preambleInfo.numberOfRaPreambles = 64; break; default: rachConfigCommon->preambleInfo.numberOfRaPreambles = 0; } rachConfigCommon->preambleInfo.numberOfRaPreambles = n; if (preamblesGroupAConfigPresent[0]) { // Deserialize preamblesGroupAConfig // ... } // powerRampingParameters bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (4,&n,bIterator); // powerRampingStep bIterator = DeserializeEnum (16,&n,bIterator); // preambleInitialReceivedTargetPower // ra-SupervisionInfo bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (11,&n,bIterator); // preambleTransMax switch (n) { case 0: rachConfigCommon->raSupervisionInfo.preambleTransMax = 3; break; case 1: rachConfigCommon->raSupervisionInfo.preambleTransMax = 4; break; case 2: rachConfigCommon->raSupervisionInfo.preambleTransMax = 5; break; case 3: rachConfigCommon->raSupervisionInfo.preambleTransMax = 6; break; case 4: rachConfigCommon->raSupervisionInfo.preambleTransMax = 7; break; case 5: rachConfigCommon->raSupervisionInfo.preambleTransMax = 8; break; case 6: rachConfigCommon->raSupervisionInfo.preambleTransMax = 10; break; case 7: rachConfigCommon->raSupervisionInfo.preambleTransMax = 20; break; case 8: rachConfigCommon->raSupervisionInfo.preambleTransMax = 50; break; case 9: rachConfigCommon->raSupervisionInfo.preambleTransMax = 100; break; case 10: rachConfigCommon->raSupervisionInfo.preambleTransMax = 200; break; default: rachConfigCommon->raSupervisionInfo.preambleTransMax = 0; } // ra-ResponseWindowSize bIterator = DeserializeEnum (8,&n,bIterator); switch (n) { case 0: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 2; break; case 1: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 3; break; case 2: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 4; break; case 3: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 5; break; case 4: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 6; break; case 5: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 7; break; case 6: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 8; break; case 7: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 10; break; default: rachConfigCommon->raSupervisionInfo.raResponseWindowSize = 0; } bIterator = DeserializeEnum (8,&n,bIterator); // mac-ContentionResolutionTimer bIterator = DeserializeInteger (&n,1,8,bIterator); //maxHARQ-Msg3Tx return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeRadioResourceConfigCommonSib (LteRrcSap::RadioResourceConfigCommonSib * radioResourceConfigCommonSib, Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeSequence (&bitset0,true,bIterator); // rach-ConfigCommon bIterator = DeserializeRachConfigCommon (&radioResourceConfigCommonSib->rachConfigCommon, bIterator); // bcch-Config bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (4,&n,bIterator); // modificationPeriodCoeff // pcch-Config bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (4,&n,bIterator); // defaultPagingCycle bIterator = DeserializeEnum (8,&n,bIterator); // nB // prach-Config std::bitset<1> prachConfigInfoPresent; bIterator = DeserializeSequence (&prachConfigInfoPresent,false,bIterator); // prach-Config -> rootSequenceIndex bIterator = DeserializeInteger (&n,0,1023,bIterator); // prach-Config -> prach-ConfigInfo if (prachConfigInfoPresent[0]) { // ... } // pdsch-ConfigCommon bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeInteger (&n,-60,50,bIterator); // referenceSignalPower bIterator = DeserializeInteger (&n,0,3,bIterator); // p-b // pusch-ConfigCommon bIterator = DeserializeSequence (&bitset0,false,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic bIterator = DeserializeSequence (&bitset0,false,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> n-SB bIterator = DeserializeInteger (&n,1,4,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> hoppingMode bIterator = DeserializeEnum (2,&n,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> pusch-HoppingOffset bIterator = DeserializeInteger (&n,0,98,bIterator); // pusch-ConfigCommon -> pusch-ConfigBasic -> enable64QAM bool dummyBoolean; bIterator = DeserializeBoolean (&dummyBoolean,bIterator); // ul-ReferenceSignalsPUSCH bIterator = DeserializeSequence (&bitset0,false,bIterator); // groupHoppingEnabled bIterator = DeserializeBoolean (&dummyBoolean,bIterator); // groupAssignmentPUSCH bIterator = DeserializeInteger (&n,0,29,bIterator); // sequenceHoppingEnabled bIterator = DeserializeBoolean (&dummyBoolean,bIterator); // cyclicShift bIterator = DeserializeInteger (&n,0,7,bIterator); // pucch-ConfigCommon bIterator = DeserializeEnum (3,&n,bIterator); // deltaPUCCH-Shift bIterator = DeserializeInteger (&n,0,98,bIterator); // nRB-CQI bIterator = DeserializeInteger (&n,0,7,bIterator); // nCS-AN bIterator = DeserializeInteger (&n,0,2047,bIterator); // n1PUCCH-AN // soundingRS-UL-ConfigCommon int choice; bIterator = DeserializeChoice (2,false,&choice,bIterator); if (choice == 0) { bIterator = DeserializeNull (bIterator); // release } if (choice == 1) { // setup // ... } // uplinkPowerControlCommon bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeInteger (&n,-126,24,bIterator); // p0-NominalPUSCH bIterator = DeserializeEnum (8,&n,bIterator); // alpha bIterator = DeserializeInteger (&n,-127,-96,bIterator); // p0-NominalPUCCH //deltaFList-PUCCH bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (3,&n,bIterator); // deltaF-PUCCH-Format1 bIterator = DeserializeEnum (3,&n,bIterator); // deltaF-PUCCH-Format1b bIterator = DeserializeEnum (4,&n,bIterator); // deltaF-PUCCH-Format2 bIterator = DeserializeEnum (3,&n,bIterator); // deltaF-PUCCH-Format2a bIterator = DeserializeEnum (3,&n,bIterator); // deltaF-PUCCH-Format2b bIterator = DeserializeInteger (&n,-1,6,bIterator); // deltaPreambleMsg3 // ul-CyclicPrefixLength bIterator = DeserializeEnum (2,&n,bIterator); return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeMeasResults (LteRrcSap::MeasResults *measResults, Buffer::Iterator bIterator) { int n; std::bitset<0> b0; std::bitset<4> measResultOptionalPresent; // bIterator = DeserializeSequence (&measResultNeighCellsPresent,true,bIterator); bIterator = DeserializeSequence (&measResultOptionalPresent,true,bIterator); // Deserialize measId bIterator = DeserializeInteger (&n, 1, MAX_MEAS_ID, bIterator); measResults->measId = n; // Deserialize measResultServCell bIterator = DeserializeSequence (&b0,false,bIterator); // Deserialize rsrpResult bIterator = DeserializeInteger (&n, 0, 97, bIterator); measResults->rsrpResult = n; // Deserialize rsrqResult bIterator = DeserializeInteger (&n, 0, 34, bIterator); measResults->rsrqResult = n; measResults->haveMeasResultNeighCells = measResultOptionalPresent[0]; measResults->haveScellsMeas = measResultOptionalPresent[3]; if ( measResults->haveMeasResultNeighCells) { int measResultNeighCellsChoice; // Deserialize measResultNeighCells bIterator = DeserializeChoice (4,false,&measResultNeighCellsChoice,bIterator); if (measResultNeighCellsChoice == 0) { // Deserialize measResultListEUTRA int numElems; bIterator = DeserializeSequenceOf (&numElems,MAX_CELL_REPORT,1,bIterator); for (int i = 0; i < numElems; i++) { LteRrcSap::MeasResultEutra measResultEutra; std::bitset<1> isCgiInfoPresent; bIterator = DeserializeSequence (&isCgiInfoPresent,false,bIterator); // PhysCellId bIterator = DeserializeInteger (&n,0,503,bIterator); measResultEutra.physCellId = n; measResultEutra.haveCgiInfo = isCgiInfoPresent[0]; if (isCgiInfoPresent[0]) { std::bitset<1> havePlmnIdentityList; bIterator = DeserializeSequence (&havePlmnIdentityList,false,bIterator); // Deserialize cellGlobalId bIterator = DeserializeSequence (&b0,false,bIterator); // Deserialize plmn-Identity bIterator = DeserializePlmnIdentity (&measResultEutra.cgiInfo.plmnIdentity,bIterator); // Deserialize CellIdentity std::bitset<28> cellId; bIterator = DeserializeBitstring (&cellId,bIterator); measResultEutra.cgiInfo.cellIdentity = cellId.to_ulong (); // Deserialize trackingAreaCode std::bitset<16> trArCo; bIterator = DeserializeBitstring (&trArCo,bIterator); measResultEutra.cgiInfo.trackingAreaCode = trArCo.to_ulong (); // Deserialize plmn-IdentityList if (havePlmnIdentityList[0]) { int numPlmnElems; bIterator = DeserializeSequenceOf (&numPlmnElems, 5, 1, bIterator); for ( int j = 0; j < numPlmnElems; j++) { uint32_t plmnId; bIterator = DeserializePlmnIdentity (&plmnId,bIterator); measResultEutra.cgiInfo.plmnIdentityList.push_back (plmnId); } } } // Deserialize measResult std::bitset<2> measResultOpts; bIterator = DeserializeSequence (&measResultOpts, true, bIterator); measResultEutra.haveRsrpResult = measResultOpts[1]; if (measResultOpts[1]) { // Deserialize rsrpResult bIterator = DeserializeInteger (&n,0,97,bIterator); measResultEutra.rsrpResult = n; } measResultEutra.haveRsrqResult = measResultOpts[0]; if (measResultOpts[0]) { // Deserialize rsrqResult bIterator = DeserializeInteger (&n,0,34,bIterator); measResultEutra.rsrqResult = n; } measResults->measResultListEutra.push_back (measResultEutra); } } if (measResultNeighCellsChoice == 1) { // Deserialize measResultListUTRA // ... } if (measResultNeighCellsChoice == 2) { // Deserialize measResultListGERAN // ... } if (measResultNeighCellsChoice == 3) { // Deserialize measResultsCDMA2000 // ... } } if (measResults->haveScellsMeas) { int numElems; bIterator = DeserializeSequenceOf (&numElems,MAX_SCELL_REPORT,1,bIterator); for (int i = 0; i < numElems; i++) { LteRrcSap::MeasResultScell measResultScell; int measScellId; // Deserialize measId bIterator = DeserializeInteger (&measScellId, 1,MAX_SCELL_REPORT,bIterator); measResultScell.servFreqId = measScellId; std::bitset<2> measResultScellPresent; bIterator = DeserializeSequence (&measResultScellPresent,true,bIterator); measResults->measScellResultList.haveMeasurementResultsServingSCells = measResultScellPresent[0]; measResults->measScellResultList.haveMeasurementResultsNeighCell = measResultScellPresent[1]; if (measResults->measScellResultList.haveMeasurementResultsServingSCells) { // Deserialize measResult std::bitset<2> measResultOpts; bIterator = DeserializeSequence (&measResultOpts, true, bIterator); measResultScell.haveRsrpResult = measResultOpts[1]; if (measResultOpts[1]) { // Deserialize rsrpResult bIterator = DeserializeInteger (&n,0,97,bIterator); measResultScell.rsrpResult = n; } measResultScell.haveRsrqResult = measResultOpts[0]; if (measResultOpts[0]) { // Deserialize rsrqResult bIterator = DeserializeInteger (&n,0,34,bIterator); measResultScell.rsrqResult = n; } } if (measResults->measScellResultList.haveMeasurementResultsNeighCell) { // Deserialize measResultBestNeighCell } measResults->measScellResultList.measResultScell.push_back (measResultScell); } } return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializePlmnIdentity (uint32_t *plmnId, Buffer::Iterator bIterator) { int n; std::bitset<1> isMccPresent; bIterator = DeserializeSequence (&isMccPresent,false,bIterator); if (isMccPresent[0]) { // Deserialize mcc // ... } // Deserialize mnc int mncDigits; int mnc = 0; bIterator = DeserializeSequenceOf (&mncDigits,3,2,bIterator); for (int j = mncDigits - 1; j >= 0; j--) { bIterator = DeserializeInteger (&n,0,9,bIterator); mnc += n * pow (10,j); } *plmnId = mnc; // cellReservedForOperatorUse bIterator = DeserializeEnum (2,&n,bIterator); return bIterator; } Buffer::Iterator RrcAsn1Header::DeserializeMeasConfig (LteRrcSap::MeasConfig * measConfig, Buffer::Iterator bIterator) { std::bitset<0> bitset0; std::bitset<2> bitset2; std::bitset<11> bitset11; int n; // measConfig bIterator = DeserializeSequence (&bitset11,true,bIterator); if (bitset11[10]) { // measObjectToRemoveList int measObjectToRemoveListElems; bIterator = DeserializeSequenceOf (&measObjectToRemoveListElems, MAX_OBJECT_ID, 1, bIterator); for (int i = 0; i < measObjectToRemoveListElems; i++) { bIterator = DeserializeInteger (&n, 1, MAX_OBJECT_ID, bIterator); measConfig->measObjectToRemoveList.push_back (n); } } if (bitset11[9]) { // measObjectToAddModList int measObjectToAddModListElems; bIterator = DeserializeSequenceOf (&measObjectToAddModListElems, MAX_OBJECT_ID, 1, bIterator); for (int i = 0; i < measObjectToAddModListElems; i++) { LteRrcSap::MeasObjectToAddMod elem; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeInteger (&n, 1, MAX_OBJECT_ID, bIterator); elem.measObjectId = n; int measObjectChoice; bIterator = DeserializeChoice (4, true, &measObjectChoice, bIterator); switch (measObjectChoice) { case 1: // Deserialize measObjectUTRA // ... break; case 2: // Deserialize measObjectGERAN // ... break; case 3: // Deserialize measObjectCDMA2000 // ... break; case 0: default: // Deserialize measObjectEUTRA std::bitset<5> measObjectEutraOpts; bIterator = DeserializeSequence (&measObjectEutraOpts, true, bIterator); // carrierFreq bIterator = DeserializeInteger (&n, 0, MAX_EARFCN, bIterator); elem.measObjectEutra.carrierFreq = n; // allowedMeasBandwidth bIterator = DeserializeEnum (6, &n, bIterator); switch (n) { case 0: elem.measObjectEutra.allowedMeasBandwidth = 6; break; case 1: elem.measObjectEutra.allowedMeasBandwidth = 15; break; case 2: elem.measObjectEutra.allowedMeasBandwidth = 25; break; case 3: elem.measObjectEutra.allowedMeasBandwidth = 50; break; case 4: elem.measObjectEutra.allowedMeasBandwidth = 75; break; case 5: default: elem.measObjectEutra.allowedMeasBandwidth = 100; break; } // presenceAntennaPort1 bIterator = DeserializeBoolean (&elem.measObjectEutra.presenceAntennaPort1, bIterator); // neighCellConfig bIterator = DeserializeBitstring (&bitset2, bIterator); elem.measObjectEutra.neighCellConfig = bitset2.to_ulong (); // offsetFreq bIterator = DeserializeQoffsetRange (&elem.measObjectEutra.offsetFreq, bIterator); if (measObjectEutraOpts[4]) { // cellsToRemoveList int numElems; bIterator = DeserializeSequenceOf (&numElems, MAX_CELL_MEAS, 1, bIterator); for (int i = 0; i < numElems; i++) { bIterator = DeserializeInteger (&n, 1, MAX_CELL_MEAS, bIterator); elem.measObjectEutra.cellsToRemoveList.push_back (n); } } if (measObjectEutraOpts[3]) { // cellsToAddModList int numElems; bIterator = DeserializeSequenceOf (&numElems, MAX_CELL_MEAS, 1, bIterator); for (int i = 0; i < numElems; i++) { LteRrcSap::CellsToAddMod cellsToAddMod; bIterator = DeserializeSequence (&bitset0, false, bIterator); // cellIndex bIterator = DeserializeInteger (&n, 1, MAX_CELL_MEAS, bIterator); cellsToAddMod.cellIndex = n; // PhysCellId bIterator = DeserializeInteger (&n, 0, 503, bIterator); cellsToAddMod.physCellId = n; // cellIndividualOffset bIterator = DeserializeQoffsetRange ( &cellsToAddMod.cellIndividualOffset, bIterator); elem.measObjectEutra.cellsToAddModList.push_back (cellsToAddMod); } } if (measObjectEutraOpts[2]) { // blackCellsToRemoveList int numElems; bIterator = DeserializeSequenceOf (&numElems, MAX_CELL_MEAS, 1, bIterator); for (int i = 0; i < numElems; i++) { bIterator = DeserializeInteger (&n, 1, MAX_CELL_MEAS, bIterator); elem.measObjectEutra.blackCellsToRemoveList.push_back (n); } } if (measObjectEutraOpts[1]) { // blackCellsToAddModList int numElems; bIterator = DeserializeSequenceOf (&numElems, MAX_CELL_MEAS, 1, bIterator); for (int i = 0; i < numElems; i++) { LteRrcSap::BlackCellsToAddMod blackCellsToAddMod; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeInteger (&n, 1, MAX_CELL_MEAS, bIterator); blackCellsToAddMod.cellIndex = n; // PhysCellIdRange std::bitset<1> isRangePresent; bIterator = DeserializeSequence (&isRangePresent, false, bIterator); // start bIterator = DeserializeInteger (&n, 0, 503, bIterator); blackCellsToAddMod.physCellIdRange.start = n; blackCellsToAddMod.physCellIdRange.haveRange = isRangePresent[0]; // initialize range to silence compiler warning blackCellsToAddMod.physCellIdRange.range = 0; if (blackCellsToAddMod.physCellIdRange.haveRange) { // range bIterator = DeserializeEnum (16, &n, bIterator); switch (n) { case 0: blackCellsToAddMod.physCellIdRange.range = 4; break; case 1: blackCellsToAddMod.physCellIdRange.range = 8; break; case 2: blackCellsToAddMod.physCellIdRange.range = 12; break; case 3: blackCellsToAddMod.physCellIdRange.range = 16; break; case 4: blackCellsToAddMod.physCellIdRange.range = 24; break; case 5: blackCellsToAddMod.physCellIdRange.range = 32; break; case 6: blackCellsToAddMod.physCellIdRange.range = 48; break; case 7: blackCellsToAddMod.physCellIdRange.range = 64; break; case 8: blackCellsToAddMod.physCellIdRange.range = 84; break; case 9: blackCellsToAddMod.physCellIdRange.range = 96; break; case 10: blackCellsToAddMod.physCellIdRange.range = 128; break; case 11: blackCellsToAddMod.physCellIdRange.range = 168; break; case 12: blackCellsToAddMod.physCellIdRange.range = 252; break; case 13: blackCellsToAddMod.physCellIdRange.range = 504; break; default: blackCellsToAddMod.physCellIdRange.range = 0; } } elem.measObjectEutra.blackCellsToAddModList.push_back (blackCellsToAddMod); } } elem.measObjectEutra.haveCellForWhichToReportCGI = measObjectEutraOpts[0]; if (measObjectEutraOpts[0]) { // cellForWhichToReportCGI bIterator = DeserializeInteger (&n, 0, 503, bIterator); elem.measObjectEutra.cellForWhichToReportCGI = n; } } measConfig->measObjectToAddModList.push_back (elem); } } if (bitset11[8]) { // reportConfigToRemoveList int reportConfigToRemoveListElems; bIterator = DeserializeSequenceOf (&reportConfigToRemoveListElems, MAX_REPORT_CONFIG_ID, 1, bIterator); for (int i = 0; i < reportConfigToRemoveListElems; i++) { bIterator = DeserializeInteger (&n, 1, MAX_REPORT_CONFIG_ID, bIterator); measConfig->reportConfigToRemoveList.push_back (n); } } if (bitset11[7]) { // reportConfigToAddModList int reportConfigToAddModListElems; bIterator = DeserializeSequenceOf (&reportConfigToAddModListElems, MAX_REPORT_CONFIG_ID, 1, bIterator); for (int i = 0; i < reportConfigToAddModListElems; i++) { LteRrcSap::ReportConfigToAddMod elem; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeInteger (&n, 1, MAX_REPORT_CONFIG_ID, bIterator); elem.reportConfigId = n; // Deserialize reportConfig int reportConfigChoice; bIterator = DeserializeChoice (2, false, &reportConfigChoice, bIterator); if (reportConfigChoice == 0) { // reportConfigEUTRA bIterator = DeserializeSequence (&bitset0, true, bIterator); // triggerType int triggerTypeChoice; bIterator = DeserializeChoice (2, false, &triggerTypeChoice, bIterator); if (triggerTypeChoice == 0) { // event elem.reportConfigEutra.triggerType = LteRrcSap::ReportConfigEutra::EVENT; bIterator = DeserializeSequence (&bitset0, false, bIterator); // eventId int eventIdChoice; bIterator = DeserializeChoice (5, true, &eventIdChoice, bIterator); switch (eventIdChoice) { case 0: elem.reportConfigEutra.eventId = LteRrcSap::ReportConfigEutra::EVENT_A1; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeThresholdEutra (&elem.reportConfigEutra.threshold1, bIterator); break; case 1: elem.reportConfigEutra.eventId = LteRrcSap::ReportConfigEutra::EVENT_A2; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeThresholdEutra (&elem.reportConfigEutra.threshold1, bIterator); break; case 2: elem.reportConfigEutra.eventId = LteRrcSap::ReportConfigEutra::EVENT_A3; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeInteger (&n, -30, 30, bIterator); elem.reportConfigEutra.a3Offset = n; bIterator = DeserializeBoolean (&elem.reportConfigEutra.reportOnLeave, bIterator); break; case 3: elem.reportConfigEutra.eventId = LteRrcSap::ReportConfigEutra::EVENT_A4; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeThresholdEutra (&elem.reportConfigEutra.threshold1, bIterator); break; case 4: default: elem.reportConfigEutra.eventId = LteRrcSap::ReportConfigEutra::EVENT_A5; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeThresholdEutra (&elem.reportConfigEutra.threshold1, bIterator); bIterator = DeserializeThresholdEutra (&elem.reportConfigEutra.threshold2, bIterator); } bIterator = DeserializeInteger (&n, 0, 30, bIterator); elem.reportConfigEutra.hysteresis = n; bIterator = DeserializeEnum (16, &n, bIterator); switch (n) { case 0: elem.reportConfigEutra.timeToTrigger = 0; break; case 1: elem.reportConfigEutra.timeToTrigger = 40; break; case 2: elem.reportConfigEutra.timeToTrigger = 64; break; case 3: elem.reportConfigEutra.timeToTrigger = 80; break; case 4: elem.reportConfigEutra.timeToTrigger = 100; break; case 5: elem.reportConfigEutra.timeToTrigger = 128; break; case 6: elem.reportConfigEutra.timeToTrigger = 160; break; case 7: elem.reportConfigEutra.timeToTrigger = 256; break; case 8: elem.reportConfigEutra.timeToTrigger = 320; break; case 9: elem.reportConfigEutra.timeToTrigger = 480; break; case 10: elem.reportConfigEutra.timeToTrigger = 512; break; case 11: elem.reportConfigEutra.timeToTrigger = 640; break; case 12: elem.reportConfigEutra.timeToTrigger = 1024; break; case 13: elem.reportConfigEutra.timeToTrigger = 1280; break; case 14: elem.reportConfigEutra.timeToTrigger = 2560; break; case 15: default: elem.reportConfigEutra.timeToTrigger = 5120; break; } } if (triggerTypeChoice == 1) { // periodical elem.reportConfigEutra.triggerType = LteRrcSap::ReportConfigEutra::PERIODICAL; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeEnum (2, &n, bIterator); if (n == 0) { elem.reportConfigEutra.purpose = LteRrcSap::ReportConfigEutra::REPORT_STRONGEST_CELLS; } else { elem.reportConfigEutra.purpose = LteRrcSap::ReportConfigEutra::REPORT_CGI; } } // triggerQuantity bIterator = DeserializeEnum (2, &n, bIterator); if (n == 0) { elem.reportConfigEutra.triggerQuantity = LteRrcSap::ReportConfigEutra::RSRP; } else { elem.reportConfigEutra.triggerQuantity = LteRrcSap::ReportConfigEutra::RSRQ; } // reportQuantity bIterator = DeserializeEnum (2, &n, bIterator); if (n == 0) { elem.reportConfigEutra.reportQuantity = LteRrcSap::ReportConfigEutra::SAME_AS_TRIGGER_QUANTITY; } else { elem.reportConfigEutra.reportQuantity = LteRrcSap::ReportConfigEutra::BOTH; } // maxReportCells bIterator = DeserializeInteger (&n, 1, MAX_CELL_REPORT, bIterator); elem.reportConfigEutra.maxReportCells = n; // reportInterval bIterator = DeserializeEnum (16, &n, bIterator); switch (n) { case 0: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS120; break; case 1: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS240; break; case 2: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS480; break; case 3: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS640; break; case 4: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS1024; break; case 5: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS2048; break; case 6: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS5120; break; case 7: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MS10240; break; case 8: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MIN1; break; case 9: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MIN6; break; case 10: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MIN12; break; case 11: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MIN30; break; case 12: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::MIN60; break; case 13: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::SPARE3; break; case 14: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::SPARE2; break; case 15: default: elem.reportConfigEutra.reportInterval = LteRrcSap::ReportConfigEutra::SPARE1; } // reportAmount bIterator = DeserializeEnum (8, &n, bIterator); switch (n) { case 0: elem.reportConfigEutra.reportAmount = 1; break; case 1: elem.reportConfigEutra.reportAmount = 2; break; case 2: elem.reportConfigEutra.reportAmount = 4; break; case 3: elem.reportConfigEutra.reportAmount = 8; break; case 4: elem.reportConfigEutra.reportAmount = 16; break; case 5: elem.reportConfigEutra.reportAmount = 32; break; case 6: elem.reportConfigEutra.reportAmount = 64; break; default: elem.reportConfigEutra.reportAmount = 0; } } if (reportConfigChoice == 1) { // ReportConfigInterRAT // ... } measConfig->reportConfigToAddModList.push_back (elem); } } if (bitset11[6]) { // measIdToRemoveList int measIdToRemoveListElems; bIterator = DeserializeSequenceOf (&measIdToRemoveListElems, MAX_MEAS_ID, 1, bIterator); for (int i = 0; i < measIdToRemoveListElems; i++) { bIterator = DeserializeInteger (&n, 1, MAX_MEAS_ID, bIterator); measConfig->measIdToRemoveList.push_back (n); } } if (bitset11[5]) { // measIdToAddModList int measIdToAddModListElems; bIterator = DeserializeSequenceOf (&measIdToAddModListElems, MAX_MEAS_ID, 1, bIterator); for (int i = 0; i < measIdToAddModListElems; i++) { LteRrcSap::MeasIdToAddMod elem; bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeInteger (&n, 1, MAX_MEAS_ID, bIterator); elem.measId = n; bIterator = DeserializeInteger (&n, 1, MAX_OBJECT_ID, bIterator); elem.measObjectId = n; bIterator = DeserializeInteger (&n, 1, MAX_REPORT_CONFIG_ID, bIterator); elem.reportConfigId = n; measConfig->measIdToAddModList.push_back (elem); } } measConfig->haveQuantityConfig = bitset11[4]; if (measConfig->haveQuantityConfig) { // quantityConfig std::bitset<4> quantityConfigOpts; bIterator = DeserializeSequence (&quantityConfigOpts, true, bIterator); if (quantityConfigOpts[3]) { // quantityConfigEUTRA bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (16, &n, bIterator); switch (n) { case 0: measConfig->quantityConfig.filterCoefficientRSRP = 0; break; case 1: measConfig->quantityConfig.filterCoefficientRSRP = 1; break; case 2: measConfig->quantityConfig.filterCoefficientRSRP = 2; break; case 3: measConfig->quantityConfig.filterCoefficientRSRP = 3; break; case 4: measConfig->quantityConfig.filterCoefficientRSRP = 4; break; case 5: measConfig->quantityConfig.filterCoefficientRSRP = 5; break; case 6: measConfig->quantityConfig.filterCoefficientRSRP = 6; break; case 7: measConfig->quantityConfig.filterCoefficientRSRP = 7; break; case 8: measConfig->quantityConfig.filterCoefficientRSRP = 8; break; case 9: measConfig->quantityConfig.filterCoefficientRSRP = 9; break; case 10: measConfig->quantityConfig.filterCoefficientRSRP = 11; break; case 11: measConfig->quantityConfig.filterCoefficientRSRP = 13; break; case 12: measConfig->quantityConfig.filterCoefficientRSRP = 15; break; case 13: measConfig->quantityConfig.filterCoefficientRSRP = 17; break; case 14: measConfig->quantityConfig.filterCoefficientRSRP = 19; break; case 15: measConfig->quantityConfig.filterCoefficientRSRP = 0; break; default: measConfig->quantityConfig.filterCoefficientRSRP = 4; } bIterator = DeserializeEnum (16, &n, bIterator); switch (n) { case 0: measConfig->quantityConfig.filterCoefficientRSRQ = 0; break; case 1: measConfig->quantityConfig.filterCoefficientRSRQ = 1; break; case 2: measConfig->quantityConfig.filterCoefficientRSRQ = 2; break; case 3: measConfig->quantityConfig.filterCoefficientRSRQ = 3; break; case 4: measConfig->quantityConfig.filterCoefficientRSRQ = 4; break; case 5: measConfig->quantityConfig.filterCoefficientRSRQ = 5; break; case 6: measConfig->quantityConfig.filterCoefficientRSRQ = 6; break; case 7: measConfig->quantityConfig.filterCoefficientRSRQ = 7; break; case 8: measConfig->quantityConfig.filterCoefficientRSRQ = 8; break; case 9: measConfig->quantityConfig.filterCoefficientRSRQ = 9; break; case 10: measConfig->quantityConfig.filterCoefficientRSRQ = 11; break; case 11: measConfig->quantityConfig.filterCoefficientRSRQ = 13; break; case 12: measConfig->quantityConfig.filterCoefficientRSRQ = 15; break; case 13: measConfig->quantityConfig.filterCoefficientRSRQ = 17; break; case 14: measConfig->quantityConfig.filterCoefficientRSRQ = 19; break; case 15: measConfig->quantityConfig.filterCoefficientRSRQ = 0; break; default: measConfig->quantityConfig.filterCoefficientRSRQ = 4; } } if (quantityConfigOpts[2]) { // quantityConfigUTRA // ... } if (quantityConfigOpts[1]) { // quantityConfigGERAN // ... } if (quantityConfigOpts[0]) { // quantityConfigCDMA2000 // ... } } measConfig->haveMeasGapConfig = bitset11[3]; if (measConfig->haveMeasGapConfig) { // measGapConfig int measGapConfigChoice; bIterator = DeserializeChoice (2, false, &measGapConfigChoice, bIterator); switch (measGapConfigChoice) { case 0: measConfig->measGapConfig.type = LteRrcSap::MeasGapConfig::RESET; bIterator = DeserializeNull (bIterator); break; case 1: default: measConfig->measGapConfig.type = LteRrcSap::MeasGapConfig::SETUP; bIterator = DeserializeSequence (&bitset0, false, bIterator); int gapOffsetChoice; bIterator = DeserializeChoice (2, true, &gapOffsetChoice, bIterator); switch (gapOffsetChoice) { case 0: measConfig->measGapConfig.gapOffsetChoice = LteRrcSap::MeasGapConfig::GP0; bIterator = DeserializeInteger (&n, 0, 39, bIterator); measConfig->measGapConfig.gapOffsetValue = n; break; case 1: default: measConfig->measGapConfig.gapOffsetChoice = LteRrcSap::MeasGapConfig::GP1; bIterator = DeserializeInteger (&n, 0, 79, bIterator); measConfig->measGapConfig.gapOffsetValue = n; } } } measConfig->haveSmeasure = bitset11[2]; if (measConfig->haveSmeasure) { // s-Measure bIterator = DeserializeInteger (&n, 0, 97, bIterator); measConfig->sMeasure = n; } if (bitset11[1]) { // preRegistrationInfoHRPD // ... } measConfig->haveSpeedStatePars = bitset11[0]; if (measConfig->haveSpeedStatePars) { // speedStatePars int speedStateParsChoice; bIterator = DeserializeChoice (2, false, &speedStateParsChoice, bIterator); switch (speedStateParsChoice) { case 0: measConfig->speedStatePars.type = LteRrcSap::SpeedStatePars::RESET; bIterator = DeserializeNull (bIterator); break; case 1: default: measConfig->speedStatePars.type = LteRrcSap::SpeedStatePars::SETUP; bIterator = DeserializeSequence (&bitset0, false, bIterator); // Deserialize mobilityStateParameters // Deserialize t-Evaluation bIterator = DeserializeEnum (8, &n, bIterator); switch (n) { case 0: measConfig->speedStatePars.mobilityStateParameters.tEvaluation = 30; break; case 1: measConfig->speedStatePars.mobilityStateParameters.tEvaluation = 60; break; case 2: measConfig->speedStatePars.mobilityStateParameters.tEvaluation = 120; break; case 3: measConfig->speedStatePars.mobilityStateParameters.tEvaluation = 180; break; case 4: measConfig->speedStatePars.mobilityStateParameters.tEvaluation = 240; break; default: measConfig->speedStatePars.mobilityStateParameters.tEvaluation = 0; } // Deserialize t-HystNormal bIterator = DeserializeEnum (8, &n, bIterator); switch (n) { case 0: measConfig->speedStatePars.mobilityStateParameters.tHystNormal = 30; break; case 1: measConfig->speedStatePars.mobilityStateParameters.tHystNormal = 60; break; case 2: measConfig->speedStatePars.mobilityStateParameters.tHystNormal = 120; break; case 3: measConfig->speedStatePars.mobilityStateParameters.tHystNormal = 180; break; case 4: measConfig->speedStatePars.mobilityStateParameters.tHystNormal = 240; break; default: measConfig->speedStatePars.mobilityStateParameters.tHystNormal = 0; } bIterator = DeserializeInteger (&n, 1, 16, bIterator); measConfig->speedStatePars.mobilityStateParameters.nCellChangeMedium = n; bIterator = DeserializeInteger (&n, 1, 16, bIterator); measConfig->speedStatePars.mobilityStateParameters.nCellChangeHigh = n; // Deserialize timeToTriggerSf bIterator = DeserializeEnum (4, &n, bIterator); measConfig->speedStatePars.timeToTriggerSf.sfMedium = (n + 1) * 25; bIterator = DeserializeEnum (4, &n, bIterator); measConfig->speedStatePars.timeToTriggerSf.sfHigh = (n + 1) * 25; } } return bIterator; } //////////////////// RrcConnectionRequest class //////////////////////// // Constructor RrcConnectionRequestHeader::RrcConnectionRequestHeader () : RrcUlCcchMessage () { m_mmec = std::bitset<8> (0ul); m_mTmsi = std::bitset<32> (0ul); m_establishmentCause = MO_SIGNALLING; m_spare = std::bitset<1> (0ul); } // Destructor RrcConnectionRequestHeader::~RrcConnectionRequestHeader () { } TypeId RrcConnectionRequestHeader::GetTypeId (void) { static TypeId tid = TypeId ("ns3::RrcConnectionRequestHeader") .SetParent<Header> () .SetGroupName("Lte") ; return tid; } void RrcConnectionRequestHeader::Print (std::ostream &os) const { os << "MMEC:" << m_mmec << std::endl; os << "MTMSI:" << m_mTmsi << std::endl; os << "EstablishmentCause:" << m_establishmentCause << std::endl; os << "Spare: " << m_spare << std::endl; } void RrcConnectionRequestHeader::PreSerialize () const { m_serializationResult = Buffer (); SerializeUlCcchMessage (1); // Serialize RRCConnectionRequest sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize criticalExtensions choice: // 2 options, selected: 0 (option: rrcConnectionRequest-r8) SerializeChoice (2,0,false); // Serialize RRCConnectionRequest-r8-IEs sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize InitialUE-Identity choice: // 2 options, selected: 0 (option: s-TMSI) SerializeChoice (2,0,false); // Serialize S-TMSI sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize mmec : MMEC ::= BIT STRING (SIZE (8)) SerializeBitstring (m_mmec); // Serialize m-TMSI ::= BIT STRING (SIZE (32)) SerializeBitstring (m_mTmsi); // Serialize establishmentCause : EstablishmentCause ::= ENUMERATED SerializeEnum (8,m_establishmentCause); // Serialize spare : BIT STRING (SIZE (1)) SerializeBitstring (std::bitset<1> ()); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionRequestHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<1> dummy; std::bitset<0> optionalOrDefaultMask; int selectedOption; bIterator = DeserializeUlCcchMessage (bIterator); // Deserialize RCConnectionRequest sequence bIterator = DeserializeSequence (&optionalOrDefaultMask,false,bIterator); // Deserialize criticalExtensions choice: bIterator = DeserializeChoice (2,false,&selectedOption,bIterator); // Deserialize RRCConnectionRequest-r8-IEs sequence bIterator = DeserializeSequence (&optionalOrDefaultMask,false,bIterator); // Deserialize InitialUE-Identity choice bIterator = DeserializeChoice (2,false,&selectedOption,bIterator); // Deserialize S-TMSI sequence bIterator = DeserializeSequence (&optionalOrDefaultMask,false,bIterator); // Deserialize mmec bIterator = DeserializeBitstring (&m_mmec,bIterator); // Deserialize m-TMSI bIterator = DeserializeBitstring (&m_mTmsi,bIterator); // Deserialize establishmentCause bIterator = DeserializeEnum (8,&selectedOption,bIterator); // Deserialize spare bIterator = DeserializeBitstring (&dummy,bIterator); return GetSerializedSize (); } void RrcConnectionRequestHeader::SetMessage (LteRrcSap::RrcConnectionRequest msg) { m_mTmsi = std::bitset<32> ((uint32_t)msg.ueIdentity); m_mmec = std::bitset<8> ((uint32_t)(msg.ueIdentity >> 32)); m_isDataSerialized = false; } LteRrcSap::RrcConnectionRequest RrcConnectionRequestHeader::GetMessage () const { LteRrcSap::RrcConnectionRequest msg; msg.ueIdentity = (((uint64_t) m_mmec.to_ulong ()) << 32) | (m_mTmsi.to_ulong ()); return msg; } std::bitset<8> RrcConnectionRequestHeader::GetMmec () const { return m_mmec; } std::bitset<32> RrcConnectionRequestHeader::GetMtmsi () const { return m_mTmsi; } //////////////////// RrcConnectionSetup class //////////////////////// RrcConnectionSetupHeader::RrcConnectionSetupHeader () { } RrcConnectionSetupHeader::~RrcConnectionSetupHeader () { } void RrcConnectionSetupHeader::Print (std::ostream &os) const { os << "rrcTransactionIdentifier: " << (int)m_rrcTransactionIdentifier << std::endl; os << "radioResourceConfigDedicated:" << std::endl; RrcAsn1Header::Print (os,m_radioResourceConfigDedicated); } void RrcConnectionSetupHeader::PreSerialize () const { m_serializationResult = Buffer (); SerializeDlCcchMessage (3); SerializeInteger (15,0,15); // Serialize RRCConnectionSetup sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize rrc-TransactionIdentifier ::=INTEGER (0..3) SerializeInteger (m_rrcTransactionIdentifier,0,3); // Serialize criticalExtensions choice: // 2 options, selected: 0 (option: c1) SerializeChoice (2,0,false); // Serialize c1 choice: // 8 options, selected: 0 (option: rrcConnectionSetup-r8) SerializeChoice (8,0,false); // Serialize rrcConnectionSetup-r8 sequence // 1 optional fields (not present). Extension marker not present. SerializeSequence (std::bitset<1> (0),false); // Serialize RadioResourceConfigDedicated sequence SerializeRadioResourceConfigDedicated (m_radioResourceConfigDedicated); // Serialize nonCriticalExtension sequence // 2 optional fields, none present. No extension marker. SerializeSequence (std::bitset<2> (0),false); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionSetupHeader::Deserialize (Buffer::Iterator bIterator) { int n; std::bitset<0> bitset0; std::bitset<1> bitset1; std::bitset<2> bitset2; bIterator = DeserializeDlCcchMessage (bIterator); bIterator = DeserializeInteger (&n,0,15,bIterator); // Deserialize RRCConnectionSetup sequence bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize rrc-TransactionIdentifier ::=INTEGER (0..3) bIterator = DeserializeInteger (&n,0,3,bIterator); m_rrcTransactionIdentifier = n; // Deserialize criticalExtensions choice int criticalExtensionChoice; bIterator = DeserializeChoice (2,false,&criticalExtensionChoice,bIterator); if (criticalExtensionChoice == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionChoice == 0) { // Deserialize c1 int c1; bIterator = DeserializeChoice (8,false,&c1,bIterator); if (c1 > 0) { // Deserialize spareX , X:=7..1 bIterator = DeserializeNull (bIterator); } else if (c1 == 0) { // Deserialize rrcConnectionSetup-r8 // 1 optional fields, no extension marker. bIterator = DeserializeSequence (&bitset1,false,bIterator); // Deserialize radioResourceConfigDedicated bIterator = DeserializeRadioResourceConfigDedicated (&m_radioResourceConfigDedicated,bIterator); if (bitset1[0]) { // Deserialize nonCriticalExtension // 2 optional fields, no extension marker. bIterator = DeserializeSequence (&bitset2,false,bIterator); // Deserialization of lateR8NonCriticalExtension and nonCriticalExtension // ... } } } return GetSerializedSize (); } void RrcConnectionSetupHeader::SetMessage (LteRrcSap::RrcConnectionSetup msg) { m_rrcTransactionIdentifier = msg.rrcTransactionIdentifier; m_radioResourceConfigDedicated = msg.radioResourceConfigDedicated; m_isDataSerialized = false; } LteRrcSap::RrcConnectionSetup RrcConnectionSetupHeader::GetMessage () const { LteRrcSap::RrcConnectionSetup msg; msg.rrcTransactionIdentifier = m_rrcTransactionIdentifier; msg.radioResourceConfigDedicated = m_radioResourceConfigDedicated; return msg; } uint8_t RrcConnectionSetupHeader::GetRrcTransactionIdentifier () const { return m_rrcTransactionIdentifier; } bool RrcConnectionSetupHeader::HavePhysicalConfigDedicated () const { return m_radioResourceConfigDedicated.havePhysicalConfigDedicated; } std::list<LteRrcSap::SrbToAddMod> RrcConnectionSetupHeader::GetSrbToAddModList () const { return m_radioResourceConfigDedicated.srbToAddModList; } std::list<LteRrcSap::DrbToAddMod> RrcConnectionSetupHeader::GetDrbToAddModList () const { return m_radioResourceConfigDedicated.drbToAddModList; } std::list<uint8_t> RrcConnectionSetupHeader::GetDrbToReleaseList () const { return m_radioResourceConfigDedicated.drbToReleaseList; } LteRrcSap::PhysicalConfigDedicated RrcConnectionSetupHeader::GetPhysicalConfigDedicated () const { return m_radioResourceConfigDedicated.physicalConfigDedicated; } LteRrcSap::RadioResourceConfigDedicated RrcConnectionSetupHeader::GetRadioResourceConfigDedicated () const { return m_radioResourceConfigDedicated; } //////////////////// RrcConnectionSetupCompleteHeader class //////////////////////// RrcConnectionSetupCompleteHeader::RrcConnectionSetupCompleteHeader () { } RrcConnectionSetupCompleteHeader::~RrcConnectionSetupCompleteHeader () { } void RrcConnectionSetupCompleteHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize DCCH message SerializeUlDcchMessage (4); // Serialize RRCConnectionSetupComplete sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize rrc-TransactionIdentifier SerializeInteger (m_rrcTransactionIdentifier,0,3); // Serialize criticalExtensions choice // 2 options, selected 0 (c1) SerializeChoice (2,0,false); // Choose spare3 NULL SerializeChoice (4,1,false); // Serialize spare3 NULL SerializeNull (); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionSetupCompleteHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; bIterator = DeserializeUlDcchMessage (bIterator); bIterator = DeserializeSequence (&bitset0,false,bIterator); int n; bIterator = DeserializeInteger (&n,0,3,bIterator); m_rrcTransactionIdentifier = n; bIterator = DeserializeChoice (2,false,&n,bIterator); if (n == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (n == 0) { // Deserialize c1 int c1Chosen; bIterator = DeserializeChoice (4,false,&c1Chosen,bIterator); if (c1Chosen == 0) { // Deserialize rrcConnectionSetupComplete-r8 // ... } else { bIterator = DeserializeNull (bIterator); } } return GetSerializedSize (); } void RrcConnectionSetupCompleteHeader::Print (std::ostream &os) const { os << "rrcTransactionIdentifier: " << (int) m_rrcTransactionIdentifier << std::endl; } void RrcConnectionSetupCompleteHeader::SetMessage (LteRrcSap::RrcConnectionSetupCompleted msg) { m_rrcTransactionIdentifier = msg.rrcTransactionIdentifier; m_isDataSerialized = false; } uint8_t RrcConnectionSetupCompleteHeader::GetRrcTransactionIdentifier () const { return m_rrcTransactionIdentifier; } LteRrcSap::RrcConnectionSetupCompleted RrcConnectionSetupCompleteHeader::GetMessage () const { LteRrcSap::RrcConnectionSetupCompleted msg; msg.rrcTransactionIdentifier = m_rrcTransactionIdentifier; return msg; } //////////////////// RrcConnectionReconfigurationCompleteHeader class //////////////////////// RrcConnectionReconfigurationCompleteHeader::RrcConnectionReconfigurationCompleteHeader () { } RrcConnectionReconfigurationCompleteHeader::~RrcConnectionReconfigurationCompleteHeader () { } void RrcConnectionReconfigurationCompleteHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize DCCH message SerializeUlDcchMessage (2); // Serialize RRCConnectionSetupComplete sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize rrc-TransactionIdentifier SerializeInteger (m_rrcTransactionIdentifier,0,3); // Serialize criticalExtensions choice // 2 options, selected 1 (criticalExtensionsFuture) SerializeChoice (2,1,false); // Choose criticalExtensionsFuture SerializeSequence (std::bitset<0> (),false); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionReconfigurationCompleteHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeUlDcchMessage (bIterator); bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeInteger (&n,0,3,bIterator); m_rrcTransactionIdentifier = n; bIterator = DeserializeChoice (2,false,&n,bIterator); if (n == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (n == 0) { // Deserialize rrcConnectionReconfigurationComplete-r8 // ... } return GetSerializedSize (); } void RrcConnectionReconfigurationCompleteHeader::Print (std::ostream &os) const { os << "rrcTransactionIdentifier: " << (int) m_rrcTransactionIdentifier << std::endl; } void RrcConnectionReconfigurationCompleteHeader::SetMessage (LteRrcSap::RrcConnectionReconfigurationCompleted msg) { m_rrcTransactionIdentifier = msg.rrcTransactionIdentifier; m_isDataSerialized = false; } LteRrcSap::RrcConnectionReconfigurationCompleted RrcConnectionReconfigurationCompleteHeader::GetMessage () const { LteRrcSap::RrcConnectionReconfigurationCompleted msg; msg.rrcTransactionIdentifier = m_rrcTransactionIdentifier; return msg; } uint8_t RrcConnectionReconfigurationCompleteHeader::GetRrcTransactionIdentifier () const { return m_rrcTransactionIdentifier; } //////////////////// RrcConnectionReconfigurationHeader class //////////////////////// RrcConnectionReconfigurationHeader::RrcConnectionReconfigurationHeader () { } RrcConnectionReconfigurationHeader::~RrcConnectionReconfigurationHeader () { } void RrcConnectionReconfigurationHeader::PreSerialize () const { m_serializationResult = Buffer (); SerializeDlDcchMessage (4); // Serialize RRCConnectionSetupComplete sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize rrc-TransactionIdentifier SerializeInteger (m_rrcTransactionIdentifier,0,3); // Serialize criticalExtensions choice // 2 options, selected 0 (c1) SerializeChoice (2,0,false); // Serialize c1 choice // 8 options, selected 0 (rrcConnectionReconfiguration-r8) SerializeChoice (8,0,false); // Serialize RRCConnectionReconfiguration-r8-IEs sequence: // 6 optional fields. Extension marker not present. std::bitset<6> options; options.set (5,m_haveMeasConfig); options.set (4,m_haveMobilityControlInfo); options.set (3,0); // No dedicatedInfoNASList options.set (2,m_haveRadioResourceConfigDedicated); options.set (1,0); // No securityConfigHO options.set (0,m_haveNonCriticalExtension); // Implemented nonCriticalExtension because compatibility with R10 - CA SerializeSequence (options,false); if (m_haveMeasConfig) { SerializeMeasConfig (m_measConfig); } if (m_haveMobilityControlInfo) { // Serialize MobilityControlInfo // 4 optional fields, extension marker present. std::bitset<4> mobCtrlIntoOptional; mobCtrlIntoOptional.set (3,m_mobilityControlInfo.haveCarrierFreq); mobCtrlIntoOptional.set (2,m_mobilityControlInfo.haveCarrierBandwidth); mobCtrlIntoOptional.set (1,0); // No additionalSpectrumEmission mobCtrlIntoOptional.set (0,m_mobilityControlInfo.haveRachConfigDedicated); SerializeSequence (mobCtrlIntoOptional,true); // Serialize targetPhysCellId SerializeInteger (m_mobilityControlInfo.targetPhysCellId,0,503); if (m_mobilityControlInfo.haveCarrierFreq) { SerializeSequence (std::bitset<1> (1),false); SerializeInteger (m_mobilityControlInfo.carrierFreq.dlCarrierFreq,0,MAX_EARFCN); SerializeInteger (m_mobilityControlInfo.carrierFreq.ulCarrierFreq,0,MAX_EARFCN); } if (m_mobilityControlInfo.haveCarrierBandwidth) { SerializeSequence (std::bitset<1> (1),false); // Serialize dl-Bandwidth switch (m_mobilityControlInfo.carrierBandwidth.dlBandwidth) { case 6: SerializeEnum (16,0); break; case 15: SerializeEnum (16,1); break; case 25: SerializeEnum (16,2); break; case 50: SerializeEnum (16,3); break; case 75: SerializeEnum (16,4); break; case 100: SerializeEnum (16,5); break; default: SerializeEnum (16,6); } // Serialize ul-Bandwidth switch (m_mobilityControlInfo.carrierBandwidth.ulBandwidth) { case 6: SerializeEnum (16,0); break; case 15: SerializeEnum (16,1); break; case 25: SerializeEnum (16,2); break; case 50: SerializeEnum (16,3); break; case 75: SerializeEnum (16,4); break; case 100: SerializeEnum (16,5); break; default: SerializeEnum (16,6); } } // Serialize t304 SerializeEnum (8,0); // Serialize newUE-Identitiy SerializeBitstring (std::bitset<16> (m_mobilityControlInfo.newUeIdentity)); // Serialize radioResourceConfigCommon SerializeRadioResourceConfigCommon (m_mobilityControlInfo.radioResourceConfigCommon); if (m_mobilityControlInfo.haveRachConfigDedicated) { SerializeSequence (std::bitset<0> (),false); SerializeInteger (m_mobilityControlInfo.rachConfigDedicated.raPreambleIndex,0,63); SerializeInteger (m_mobilityControlInfo.rachConfigDedicated.raPrachMaskIndex,0,15); } } if (m_haveRadioResourceConfigDedicated) { // Serialize RadioResourceConfigDedicated SerializeRadioResourceConfigDedicated (m_radioResourceConfigDedicated); } if (m_haveNonCriticalExtension) { // Serialize NonCriticalExtension RRCConnectionReconfiguration-v890-IEs sequence: // 2 optional fields. Extension marker not present. std::bitset<2> noncriticalExtension_v890; noncriticalExtension_v890.set (1,0); // No lateNonCriticalExtension noncriticalExtension_v890.set (0,m_haveNonCriticalExtension); // Implemented nonCriticalExtension because compatibility with R10 - CA //Enable RRCCoonectionReconfiguration-v920-IEs SerializeSequence (noncriticalExtension_v890,false); // Serialize NonCriticalExtension RRCConnectionReconfiguration-v920-IEs sequence: // 3 optional fields. Extension marker not present. std::bitset<3> noncriticalExtension_v920; noncriticalExtension_v920.set (1,0); // No otehrConfig-r9 noncriticalExtension_v920.set (1,0); // No fullConfig-r9 //Enable RRCCoonectionReconfiguration-v1020-IEs noncriticalExtension_v920.set (0,m_haveNonCriticalExtension); // Implemented nonCriticalExtension because compatibility with R10 - CA SerializeSequence (noncriticalExtension_v920,false); SerializeNonCriticalExtensionConfiguration (m_nonCriticalExtension); //Serializing RRCConnectionReconfiguration-r8-IEs } // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionReconfigurationHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; bIterator = DeserializeDlDcchMessage (bIterator); // RRCConnectionReconfiguration sequence bIterator = DeserializeSequence (&bitset0,false,bIterator); // rrc-TransactionIdentifier int n; bIterator = DeserializeInteger (&n,0,3,bIterator); m_rrcTransactionIdentifier = n; // criticalExtensions int sel; bIterator = DeserializeChoice (2,false,&sel,bIterator); if (sel == 1) { // criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (sel == 0) { // c1 int c1Chosen; bIterator = DeserializeChoice (8,false,&c1Chosen,bIterator); if (c1Chosen > 0) { bIterator = DeserializeNull (bIterator); } else if (c1Chosen == 0) { // rrcConnectionReconfiguration-r8 std::bitset<6> rrcConnRecOpts; bIterator = DeserializeSequence (&rrcConnRecOpts,false,bIterator); m_haveMeasConfig = rrcConnRecOpts[5]; if (m_haveMeasConfig) { bIterator = DeserializeMeasConfig (&m_measConfig, bIterator); } m_haveMobilityControlInfo = rrcConnRecOpts[4]; if (m_haveMobilityControlInfo) { // mobilityControlInfo std::bitset<4> mobCtrlOpts; bIterator = DeserializeSequence (&mobCtrlOpts,true,bIterator); // PhysCellId bIterator = DeserializeInteger (&n,0,503,bIterator); m_mobilityControlInfo.targetPhysCellId = n; // carrierFreq m_mobilityControlInfo.haveCarrierFreq = mobCtrlOpts[3]; if (m_mobilityControlInfo.haveCarrierFreq) { std::bitset<1> ulCarrierFreqPresent; bIterator = DeserializeSequence (&ulCarrierFreqPresent,false,bIterator); bIterator = DeserializeInteger (&n,0,MAX_EARFCN,bIterator); m_mobilityControlInfo.carrierFreq.dlCarrierFreq = n; if (ulCarrierFreqPresent[0]) { bIterator = DeserializeInteger (&n,0,MAX_EARFCN,bIterator); m_mobilityControlInfo.carrierFreq.ulCarrierFreq = n; } } // carrierBandwidth m_mobilityControlInfo.haveCarrierBandwidth = mobCtrlOpts[2]; if (m_mobilityControlInfo.haveCarrierBandwidth) { std::bitset<1> ulBandwidthPresent; bIterator = DeserializeSequence (&ulBandwidthPresent,false,bIterator); bIterator = DeserializeEnum (16,&n,bIterator); switch (n) { case 0: m_mobilityControlInfo.carrierBandwidth.dlBandwidth = 6; break; case 1: m_mobilityControlInfo.carrierBandwidth.dlBandwidth = 15; break; case 2: m_mobilityControlInfo.carrierBandwidth.dlBandwidth = 25; break; case 3: m_mobilityControlInfo.carrierBandwidth.dlBandwidth = 50; break; case 4: m_mobilityControlInfo.carrierBandwidth.dlBandwidth = 75; break; case 5: m_mobilityControlInfo.carrierBandwidth.dlBandwidth = 100; break; case 6: m_mobilityControlInfo.carrierBandwidth.dlBandwidth = 0; break; } if (ulBandwidthPresent[0]) { bIterator = DeserializeEnum (16,&n,bIterator); switch (n) { case 0: m_mobilityControlInfo.carrierBandwidth.ulBandwidth = 6; break; case 1: m_mobilityControlInfo.carrierBandwidth.ulBandwidth = 15; break; case 2: m_mobilityControlInfo.carrierBandwidth.ulBandwidth = 25; break; case 3: m_mobilityControlInfo.carrierBandwidth.ulBandwidth = 50; break; case 4: m_mobilityControlInfo.carrierBandwidth.ulBandwidth = 75; break; case 5: m_mobilityControlInfo.carrierBandwidth.ulBandwidth = 100; break; case 6: m_mobilityControlInfo.carrierBandwidth.ulBandwidth = 0; break; } } } // additionalSpectrumEmission if (mobCtrlOpts[1]) { // ... } // t304 bIterator = DeserializeEnum (8,&n,bIterator); // newUE-Identity std::bitset<16> cRnti; bIterator = DeserializeBitstring (&cRnti, bIterator); m_mobilityControlInfo.newUeIdentity = cRnti.to_ulong (); // radioResourceConfigCommon bIterator = DeserializeRadioResourceConfigCommon (&m_mobilityControlInfo.radioResourceConfigCommon, bIterator); m_mobilityControlInfo.haveRachConfigDedicated = mobCtrlOpts[0]; if (m_mobilityControlInfo.haveRachConfigDedicated) { bIterator = DeserializeSequence (&bitset0, false, bIterator); bIterator = DeserializeInteger (&n,0,63, bIterator); m_mobilityControlInfo.rachConfigDedicated.raPreambleIndex = n; bIterator = DeserializeInteger (&n,0,15, bIterator); m_mobilityControlInfo.rachConfigDedicated.raPrachMaskIndex = n; } } // dedicatedInfoNASList if (rrcConnRecOpts[3]) { // ... } // radioResourceConfigDedicated m_haveRadioResourceConfigDedicated = rrcConnRecOpts[2]; if (m_haveRadioResourceConfigDedicated) { bIterator = DeserializeRadioResourceConfigDedicated (&m_radioResourceConfigDedicated,bIterator); } // securityConfigHO if (rrcConnRecOpts[1]) { // ... } // nonCriticalExtension m_haveNonCriticalExtension = rrcConnRecOpts[0]; if (m_haveNonCriticalExtension) { bIterator = DeserializeNonCriticalExtensionConfig (&m_nonCriticalExtension,bIterator); // ... } } } return GetSerializedSize (); } void RrcConnectionReconfigurationHeader::Print (std::ostream &os) const { os << "rrcTransactionIdentifier: " << (int) m_rrcTransactionIdentifier << std::endl; os << "haveMeasConfig: " << m_haveMeasConfig << std::endl; if (m_haveMeasConfig) { if (!m_measConfig.measObjectToRemoveList.empty ()) { os << " measObjectToRemoveList: "; std::list<uint8_t> auxList = m_measConfig.measObjectToRemoveList; std::list<uint8_t>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << (int) *it << ", "; } os << std::endl; } if (!m_measConfig.reportConfigToRemoveList.empty ()) { os << " reportConfigToRemoveList: "; std::list<uint8_t> auxList = m_measConfig.reportConfigToRemoveList; std::list<uint8_t>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << (int) *it << ", "; } os << std::endl; } if (!m_measConfig.measIdToRemoveList.empty ()) { os << " measIdToRemoveList: "; std::list<uint8_t> auxList = m_measConfig.measIdToRemoveList; std::list<uint8_t>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << (int) *it << ", "; } os << std::endl; } if (!m_measConfig.measObjectToAddModList.empty ()) { os << " measObjectToAddMod: " << std::endl; std::list<LteRrcSap::MeasObjectToAddMod> auxList = m_measConfig.measObjectToAddModList; std::list<LteRrcSap::MeasObjectToAddMod>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << " measObjectId: " << (int)it->measObjectId << std::endl; os << " carrierFreq: " << (int)it->measObjectEutra.carrierFreq << std::endl; os << " allowedMeasBandwidth: " << (int)it->measObjectEutra.allowedMeasBandwidth << std::endl; os << " presenceAntennaPort1: " << it->measObjectEutra.presenceAntennaPort1 << std::endl; os << " neighCellConfig: " << (int) it->measObjectEutra.neighCellConfig << std::endl; os << " offsetFreq: " << (int)it->measObjectEutra.offsetFreq << std::endl; if (!it->measObjectEutra.cellsToRemoveList.empty ()) { os << " cellsToRemoveList: "; std::list<uint8_t> auxList = it->measObjectEutra.cellsToRemoveList; std::list<uint8_t>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << (int) *it << ", "; } os << std::endl; } if (!it->measObjectEutra.blackCellsToRemoveList.empty ()) { os << " blackCellsToRemoveList: "; std::list<uint8_t> auxList = it->measObjectEutra.blackCellsToRemoveList; std::list<uint8_t>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << (int) *it << ", "; } os << std::endl; } if (!it->measObjectEutra.cellsToAddModList.empty ()) { os << " cellsToAddModList: " << std::endl; std::list<LteRrcSap::CellsToAddMod> auxList = it->measObjectEutra.cellsToAddModList; std::list<LteRrcSap::CellsToAddMod>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << " cellIndex: " << (int)it->cellIndex << std::endl; os << " physCellId: " << (int)it->physCellId << std::endl; os << " cellIndividualOffset: " << (int)it->cellIndividualOffset << std::endl; os << " ------ " << std::endl; } } if (!it->measObjectEutra.blackCellsToAddModList.empty ()) { os << " blackCellsToAddModList: " << std::endl; std::list<LteRrcSap::BlackCellsToAddMod> auxList = it->measObjectEutra.blackCellsToAddModList; std::list<LteRrcSap::BlackCellsToAddMod>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << " cellIndex: " << (int)it->cellIndex << std::endl; os << " physCellIdRange.start: " << (int)it->physCellIdRange.start << std::endl; os << " physCellIdRange.haveRange: " << it->physCellIdRange.haveRange << std::endl; os << " physCellIdRange.range: " << (int)it->physCellIdRange.range << std::endl; os << " ------ " << std::endl; } } os << " haveCellForWhichToReportCGI: " << it->measObjectEutra.haveCellForWhichToReportCGI << std::endl; os << " cellForWhichToReportCGI: " << (int)it->measObjectEutra.cellForWhichToReportCGI << std::endl; os << " ------------- " << std::endl; } } if (!m_measConfig.reportConfigToAddModList.empty ()) { os << " reportConfigToAddModList: " << std::endl; std::list<LteRrcSap::ReportConfigToAddMod> auxList = m_measConfig.reportConfigToAddModList; std::list<LteRrcSap::ReportConfigToAddMod>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << " reportConfigId: " << (int)it->reportConfigId << std::endl; os << " reportConfigEutra.triggerType " << (int)it->reportConfigEutra.triggerType << std::endl; if (it->reportConfigEutra.triggerType == LteRrcSap::ReportConfigEutra::EVENT) { os << " reportConfigEutra.eventId " << (int)it->reportConfigEutra.eventId << std::endl; if (it->reportConfigEutra.eventId == LteRrcSap::ReportConfigEutra::EVENT_A3) { os << " reportConfigEutra.reportOnLeave " << (int)it->reportConfigEutra.reportOnLeave << std::endl; os << " reportConfigEutra.a3Offset " << (int)it->reportConfigEutra.a3Offset << std::endl; } else { os << " reportConfigEutra.threshold1.choice " << (int)it->reportConfigEutra.threshold1.choice << std::endl; os << " reportConfigEutra.threshold1.range " << (int)it->reportConfigEutra.threshold1.range << std::endl; if (it->reportConfigEutra.eventId == LteRrcSap::ReportConfigEutra::EVENT_A5) { os << " reportConfigEutra.threshold2.choice " << (int)it->reportConfigEutra.threshold2.choice << std::endl; os << " reportConfigEutra.threshold2.range " << (int)it->reportConfigEutra.threshold2.range << std::endl; } } os << " reportConfigEutra.hysteresis " << (int)it->reportConfigEutra.hysteresis << std::endl; os << " reportConfigEutra.timeToTrigger " << (int)it->reportConfigEutra.timeToTrigger << std::endl; } else { os << " reportConfigEutra.purpose " << (int)it->reportConfigEutra.purpose << std::endl; } os << " reportConfigEutra.triggerQuantity " << (int)it->reportConfigEutra.triggerQuantity << std::endl; os << " reportConfigEutra.reportQuantity " << (int)it->reportConfigEutra.reportQuantity << std::endl; os << " reportConfigEutra.maxReportCells " << (int)it->reportConfigEutra.maxReportCells << std::endl; os << " reportConfigEutra.reportInterval " << (int)it->reportConfigEutra.reportInterval << std::endl; os << " reportConfigEutra.reportAmount " << (int)it->reportConfigEutra.reportAmount << std::endl; } } if (!m_measConfig.measIdToAddModList.empty ()) { os << " measIdToAddModList: " << std::endl; std::list<LteRrcSap::MeasIdToAddMod> auxList = m_measConfig.measIdToAddModList; std::list<LteRrcSap::MeasIdToAddMod>::iterator it = auxList.begin (); for (; it != auxList.end (); it++) { os << " measId: " << (int)it->measId << std::endl; os << " measObjectId: " << (int)it->measObjectId << std::endl; os << " reportConfigId: " << (int)it->reportConfigId << std::endl; os << " ------ " << std::endl; } } os << " haveQuantityConfig: " << m_measConfig.haveQuantityConfig << std::endl; if (m_measConfig.haveQuantityConfig) { os << " filterCoefficientRSRP: " << (int)m_measConfig.quantityConfig.filterCoefficientRSRP << std::endl; os << " filterCoefficientRSRQ:" << (int)m_measConfig.quantityConfig.filterCoefficientRSRQ << std::endl; } os << " haveMeasGapConfig: " << m_measConfig.haveMeasGapConfig << std::endl; if (m_measConfig.haveMeasGapConfig) { os << " measGapConfig.type: " << m_measConfig.measGapConfig.type << std::endl; os << " measGapConfig.gap (gap0/1,value): (" << m_measConfig.measGapConfig.gapOffsetChoice << "," << (int) m_measConfig.measGapConfig.gapOffsetValue << ")" << std::endl; } os << " haveSmeasure: " << m_measConfig.haveSmeasure << std::endl; if (m_measConfig.haveSmeasure) { os << " sMeasure: " << (int) m_measConfig.sMeasure << std::endl; } os << " haveSpeedStatePars: " << m_measConfig.haveSpeedStatePars << std::endl; if (m_measConfig.haveSpeedStatePars) { os << " speedStatePars.type: " << m_measConfig.speedStatePars.type << std::endl; os << " speedStatePars.mobilityStateParameters.tEvaluation: " << (int)m_measConfig.speedStatePars.mobilityStateParameters.tEvaluation << std::endl; os << " speedStatePars.mobilityStateParameters.tHystNormal: " << (int)m_measConfig.speedStatePars.mobilityStateParameters.tHystNormal << std::endl; os << " speedStatePars.mobilityStateParameters.nCellChangeMedium: " << (int)m_measConfig.speedStatePars.mobilityStateParameters.nCellChangeMedium << std::endl; os << " speedStatePars.mobilityStateParameters.nCellChangeHigh: " << (int)m_measConfig.speedStatePars.mobilityStateParameters.nCellChangeHigh << std::endl; os << " speedStatePars.timeToTriggerSf.sfMedium: " << (int)m_measConfig.speedStatePars.timeToTriggerSf.sfMedium << std::endl; os << " speedStatePars.timeToTriggerSf.sfHigh: " << (int)m_measConfig.speedStatePars.timeToTriggerSf.sfHigh << std::endl; } } os << "haveMobilityControlInfo: " << m_haveMobilityControlInfo << std::endl; if (m_haveMobilityControlInfo) { os << "targetPhysCellId: " << (int)m_mobilityControlInfo.targetPhysCellId << std::endl; os << "haveCarrierFreq: " << m_mobilityControlInfo.haveCarrierFreq << std::endl; if (m_mobilityControlInfo.haveCarrierFreq) { os << " carrierFreq.dlCarrierFreq: " << (int) m_mobilityControlInfo.carrierFreq.dlCarrierFreq << std::endl; os << " carrierFreq.dlCarrierFreq: " << (int) m_mobilityControlInfo.carrierFreq.ulCarrierFreq << std::endl; } os << "haveCarrierBandwidth: " << m_mobilityControlInfo.haveCarrierBandwidth << std::endl; if (m_mobilityControlInfo.haveCarrierBandwidth) { os << " carrierBandwidth.dlBandwidth: " << (int) m_mobilityControlInfo.carrierBandwidth.dlBandwidth << std::endl; os << " carrierBandwidth.ulBandwidth: " << (int) m_mobilityControlInfo.carrierBandwidth.ulBandwidth << std::endl; } os << "newUeIdentity: " << (int) m_mobilityControlInfo.newUeIdentity << std::endl; os << "haveRachConfigDedicated: " << m_mobilityControlInfo.haveRachConfigDedicated << std::endl; if (m_mobilityControlInfo.haveRachConfigDedicated) { os << "raPreambleIndex: " << (int) m_mobilityControlInfo.rachConfigDedicated.raPreambleIndex << std::endl; os << "raPrachMaskIndex: " << (int) m_mobilityControlInfo.rachConfigDedicated.raPrachMaskIndex << std::endl; } } os << "haveRadioResourceConfigDedicated: " << m_haveRadioResourceConfigDedicated << std::endl; if (m_haveRadioResourceConfigDedicated) { RrcAsn1Header::Print (os,m_radioResourceConfigDedicated); } } void RrcConnectionReconfigurationHeader::SetMessage (LteRrcSap::RrcConnectionReconfiguration msg) { m_rrcTransactionIdentifier = msg.rrcTransactionIdentifier; m_haveMeasConfig = msg.haveMeasConfig; m_measConfig = msg.measConfig; m_haveMobilityControlInfo = msg.haveMobilityControlInfo; m_mobilityControlInfo = msg.mobilityControlInfo; m_haveRadioResourceConfigDedicated = msg.haveRadioResourceConfigDedicated; m_radioResourceConfigDedicated = msg.radioResourceConfigDedicated; m_haveNonCriticalExtension = msg.haveNonCriticalExtension; m_nonCriticalExtension = msg.nonCriticalExtension; m_isDataSerialized = false; } LteRrcSap::RrcConnectionReconfiguration RrcConnectionReconfigurationHeader::GetMessage () const { LteRrcSap::RrcConnectionReconfiguration msg; msg.rrcTransactionIdentifier = m_rrcTransactionIdentifier; msg.haveMeasConfig = m_haveMeasConfig; msg.measConfig = m_measConfig; msg.haveMobilityControlInfo = m_haveMobilityControlInfo; msg.mobilityControlInfo = m_mobilityControlInfo; msg.haveRadioResourceConfigDedicated = m_haveRadioResourceConfigDedicated; msg.radioResourceConfigDedicated = m_radioResourceConfigDedicated; msg.haveNonCriticalExtension = m_haveNonCriticalExtension; msg.nonCriticalExtension = m_nonCriticalExtension; return msg; } uint8_t RrcConnectionReconfigurationHeader::GetRrcTransactionIdentifier () const { return m_rrcTransactionIdentifier; } bool RrcConnectionReconfigurationHeader::GetHaveMeasConfig () { return m_haveMeasConfig; } LteRrcSap::MeasConfig RrcConnectionReconfigurationHeader::GetMeasConfig () { return m_measConfig; } bool RrcConnectionReconfigurationHeader::GetHaveMobilityControlInfo () { return m_haveMobilityControlInfo; } LteRrcSap::MobilityControlInfo RrcConnectionReconfigurationHeader::GetMobilityControlInfo () { return m_mobilityControlInfo; } bool RrcConnectionReconfigurationHeader::GetHaveRadioResourceConfigDedicated () { return m_haveRadioResourceConfigDedicated; } LteRrcSap::RadioResourceConfigDedicated RrcConnectionReconfigurationHeader::GetRadioResourceConfigDedicated () { return m_radioResourceConfigDedicated; } bool RrcConnectionReconfigurationHeader::GetHaveNonCriticalExtensionConfig () { return m_haveNonCriticalExtension; } LteRrcSap::NonCriticalExtensionConfiguration RrcConnectionReconfigurationHeader::GetNonCriticalExtensionConfig () { return m_nonCriticalExtension; } bool RrcConnectionReconfigurationHeader::HavePhysicalConfigDedicated () const { return m_radioResourceConfigDedicated.havePhysicalConfigDedicated; } std::list<LteRrcSap::SrbToAddMod> RrcConnectionReconfigurationHeader::GetSrbToAddModList () const { return m_radioResourceConfigDedicated.srbToAddModList; } std::list<LteRrcSap::DrbToAddMod> RrcConnectionReconfigurationHeader::GetDrbToAddModList () const { return m_radioResourceConfigDedicated.drbToAddModList; } std::list<uint8_t> RrcConnectionReconfigurationHeader::GetDrbToReleaseList () const { return m_radioResourceConfigDedicated.drbToReleaseList; } LteRrcSap::PhysicalConfigDedicated RrcConnectionReconfigurationHeader::GetPhysicalConfigDedicated () const { return m_radioResourceConfigDedicated.physicalConfigDedicated; } //////////////////// HandoverPreparationInfoHeader class //////////////////////// HandoverPreparationInfoHeader::HandoverPreparationInfoHeader () { } void HandoverPreparationInfoHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize HandoverPreparationInformation sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize criticalExtensions choice // 2 options, selected 0 (c1) SerializeChoice (2,0,false); // Serialize c1 choice // 8 options, selected 0 (handoverPreparationInformation-r8) SerializeChoice (8,0,false); // Serialize HandoverPreparationInformation-r8-IEs sequence // 4 optional fields, no extension marker. std::bitset<4> handoverPrepInfoOpts; handoverPrepInfoOpts.set (3,1); // as-Config present handoverPrepInfoOpts.set (2,0); // rrm-Config not present handoverPrepInfoOpts.set (1,0); // as-Context not present handoverPrepInfoOpts.set (0,0); // nonCriticalExtension not present SerializeSequence (handoverPrepInfoOpts,false); // Serialize ue-RadioAccessCapabilityInfo SerializeSequenceOf (0,MAX_RAT_CAPABILITIES,0); // Serialize as-Config SerializeSequence (std::bitset<0> (),true); // Serialize sourceMeasConfig SerializeMeasConfig (m_asConfig.sourceMeasConfig); // Serialize sourceRadioResourceConfig SerializeRadioResourceConfigDedicated (m_asConfig.sourceRadioResourceConfig); // Serialize sourceSecurityAlgorithmConfig SerializeSequence (std::bitset<0> (),false); // cipheringAlgorithm SerializeEnum (8,0); // integrityProtAlgorithm SerializeEnum (8,0); // Serialize sourceUE-Identity SerializeBitstring (std::bitset<16> (m_asConfig.sourceUeIdentity)); // Serialize sourceMasterInformationBlock SerializeSequence (std::bitset<0> (),false); SerializeEnum (6,m_asConfig.sourceMasterInformationBlock.dlBandwidth); // dl-Bandwidth SerializeSequence (std::bitset<0> (),false); // phich-Config sequence SerializeEnum (2,0); // phich-Duration SerializeEnum (4,0); // phich-Resource SerializeBitstring (std::bitset<8> (m_asConfig.sourceMasterInformationBlock.systemFrameNumber)); // systemFrameNumber SerializeBitstring (std::bitset<10> (321)); // spare // Serialize sourceSystemInformationBlockType1 sequence SerializeSystemInformationBlockType1 (m_asConfig.sourceSystemInformationBlockType1); // Serialize sourceSystemInformationBlockType2 SerializeSystemInformationBlockType2 (m_asConfig.sourceSystemInformationBlockType2); // Serialize AntennaInfoCommon SerializeSequence (std::bitset<0> (0),false); SerializeEnum (4,0); // antennaPortsCount // Serialize sourceDlCarrierFreq SerializeInteger (m_asConfig.sourceDlCarrierFreq,0,MAX_EARFCN); // Finish serialization FinalizeSerialization (); } uint32_t HandoverPreparationInfoHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; // Deserialize HandoverPreparationInformation sequence // 0 optional fields, no extension marker bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize criticalExtensions choice int criticalExtensionsChosen; bIterator = DeserializeChoice (2,false,&criticalExtensionsChosen,bIterator); if (criticalExtensionsChosen == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionsChosen == 0) { // Deserialize c1 choice int c1Chosen; bIterator = DeserializeChoice (8,false,&c1Chosen,bIterator); if (c1Chosen > 0) { bIterator = DeserializeNull (bIterator); } else if (c1Chosen == 0) { // Deserialize handoverPreparationInformation-r8 std::bitset<4> handoverPrepInfoOpts; bIterator = DeserializeSequence (&handoverPrepInfoOpts,false,bIterator); // Deserialize ue-RadioAccessCapabilityInfo bIterator = DeserializeSequenceOf (&n,MAX_RAT_CAPABILITIES,0,bIterator); for (int i = 0; i < n; i++) { // Deserialize UE-CapabilityRAT-Container // ... } if (handoverPrepInfoOpts[3]) { // Deserialize as-Config sequence bIterator = DeserializeSequence (&bitset0,true,bIterator); // Deserialize sourceMeasConfig bIterator = DeserializeMeasConfig (&m_asConfig.sourceMeasConfig, bIterator); // Deserialize sourceRadioResourceConfig bIterator = DeserializeRadioResourceConfigDedicated (&m_asConfig.sourceRadioResourceConfig,bIterator); // Deserialize sourceSecurityAlgorithmConfig bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (8,&n,bIterator); // cipheringAlgorithm bIterator = DeserializeEnum (8,&n,bIterator); // integrityProtAlgorithm // Deserialize sourceUE-Identity std::bitset<16> cRnti; bIterator = DeserializeBitstring (&cRnti,bIterator); m_asConfig.sourceUeIdentity = cRnti.to_ulong (); // Deserialize sourceMasterInformationBlock bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (6,&n,bIterator); // dl-Bandwidth m_asConfig.sourceMasterInformationBlock.dlBandwidth = n; // phich-Config bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (2,&n,bIterator); // phich-Duration bIterator = DeserializeEnum (4,&n,bIterator); // phich-Resource // systemFrameNumber std::bitset<8> systemFrameNumber; bIterator = DeserializeBitstring (&systemFrameNumber,bIterator); m_asConfig.sourceMasterInformationBlock.systemFrameNumber = systemFrameNumber.to_ulong (); // spare std::bitset<10> spare; bIterator = DeserializeBitstring (&spare,bIterator); // Deserialize sourceSystemInformationBlockType1 bIterator = DeserializeSystemInformationBlockType1 (&m_asConfig.sourceSystemInformationBlockType1,bIterator); // Deserialize sourceSystemInformationBlockType2 bIterator = DeserializeSystemInformationBlockType2 (&m_asConfig.sourceSystemInformationBlockType2,bIterator); // Deserialize antennaInfoCommon bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeEnum (4,&n,bIterator); // antennaPortsCount // Deserialize sourceDl-CarrierFreq bIterator = DeserializeInteger (&n,0,MAX_EARFCN,bIterator); m_asConfig.sourceDlCarrierFreq = n; } if (handoverPrepInfoOpts[2]) { // Deserialize rrm-Config // ... } if (handoverPrepInfoOpts[1]) { // Deserialize as-Context // ... } if (handoverPrepInfoOpts[0]) { // Deserialize nonCriticalExtension // ... } } } return GetSerializedSize (); } void HandoverPreparationInfoHeader::Print (std::ostream &os) const { RrcAsn1Header::Print (os,m_asConfig.sourceRadioResourceConfig); os << "sourceUeIdentity: " << m_asConfig.sourceUeIdentity << std::endl; os << "dlBandwidth: " << (int)m_asConfig.sourceMasterInformationBlock.dlBandwidth << std::endl; os << "systemFrameNumber: " << (int)m_asConfig.sourceMasterInformationBlock.systemFrameNumber << std::endl; os << "plmnIdentityInfo.plmnIdentity: " << (int) m_asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.plmnIdentityInfo.plmnIdentity << std::endl; os << "cellAccessRelatedInfo.cellIdentity " << (int)m_asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.cellIdentity << std::endl; os << "cellAccessRelatedInfo.csgIndication: " << m_asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.csgIndication << std::endl; os << "cellAccessRelatedInfo.csgIdentity: " << (int)m_asConfig.sourceSystemInformationBlockType1.cellAccessRelatedInfo.csgIdentity << std::endl; os << "sourceDlCarrierFreq: " << m_asConfig.sourceDlCarrierFreq << std::endl; } void HandoverPreparationInfoHeader::SetMessage (LteRrcSap::HandoverPreparationInfo msg) { m_asConfig = msg.asConfig; m_isDataSerialized = false; } LteRrcSap::HandoverPreparationInfo HandoverPreparationInfoHeader::GetMessage () const { LteRrcSap::HandoverPreparationInfo msg; msg.asConfig = m_asConfig; return msg; } LteRrcSap::AsConfig HandoverPreparationInfoHeader::GetAsConfig () const { return m_asConfig; } //////////////////// RrcConnectionReestablishmentRequestHeader class //////////////////////// RrcConnectionReestablishmentRequestHeader::RrcConnectionReestablishmentRequestHeader () { } RrcConnectionReestablishmentRequestHeader::~RrcConnectionReestablishmentRequestHeader () { } void RrcConnectionReestablishmentRequestHeader::PreSerialize () const { m_serializationResult = Buffer (); SerializeUlCcchMessage (0); // Serialize RrcConnectionReestablishmentReques sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize criticalExtensions choice // chosen: rrcConnectionReestablishmentRequest-r8 SerializeChoice (2,0,false); // Serialize RRCConnectionReestablishmentRequest-r8-IEs sequence // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize ue-Identity SerializeSequence (std::bitset<0> (),false); // Serialize c-RNTI SerializeBitstring (std::bitset<16> (m_ueIdentity.cRnti)); // Serialize physCellId SerializeInteger (m_ueIdentity.physCellId,0,503); // Serialize shortMAC-I SerializeBitstring (std::bitset<16> (0)); // Serialize ReestablishmentCause switch (m_reestablishmentCause) { case LteRrcSap::RECONFIGURATION_FAILURE: SerializeEnum (4,0); break; case LteRrcSap::HANDOVER_FAILURE: SerializeEnum (4,1); break; case LteRrcSap::OTHER_FAILURE: SerializeEnum (4,2); break; default: SerializeEnum (4,3); } // Serialize spare SerializeBitstring (std::bitset<2> (0)); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionReestablishmentRequestHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeUlCcchMessage (bIterator); // Deserialize RrcConnectionReestablishmentRequest sequence // 0 optional fields, no extension marker bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize criticalExtensions choice bIterator = DeserializeChoice (2,false,&n,bIterator); if ( n == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if ( n == 0) { // Deserialize RRCConnectionReestablishmentRequest-r8-IEs bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize ReestabUE-Identity sequence bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize c-RNTI std::bitset<16> cRnti; bIterator = DeserializeBitstring (&cRnti,bIterator); m_ueIdentity.cRnti = cRnti.to_ulong (); // Deserialize physCellId int physCellId; bIterator = DeserializeInteger (&physCellId,0,503,bIterator); m_ueIdentity.physCellId = physCellId; // Deserialize shortMAC-I std::bitset<16> shortMacI; bIterator = DeserializeBitstring (&shortMacI,bIterator); // Deserialize ReestablishmentCause int reestCs; bIterator = DeserializeEnum (4,&reestCs,bIterator); switch (reestCs) { case 0: m_reestablishmentCause = LteRrcSap::RECONFIGURATION_FAILURE; break; case 1: m_reestablishmentCause = LteRrcSap::HANDOVER_FAILURE; break; case 2: m_reestablishmentCause = LteRrcSap::OTHER_FAILURE; break; case 3: break; } // Deserialize spare std::bitset<2> spare; bIterator = DeserializeBitstring (&spare,bIterator); } return GetSerializedSize (); } void RrcConnectionReestablishmentRequestHeader::Print (std::ostream &os) const { os << "ueIdentity.cRnti: " << (int)m_ueIdentity.cRnti << std::endl; os << "ueIdentity.physCellId: " << (int)m_ueIdentity.physCellId << std::endl; os << "m_reestablishmentCause: " << m_reestablishmentCause << std::endl; } void RrcConnectionReestablishmentRequestHeader::SetMessage (LteRrcSap::RrcConnectionReestablishmentRequest msg) { m_ueIdentity = msg.ueIdentity; m_reestablishmentCause = msg.reestablishmentCause; m_isDataSerialized = false; } LteRrcSap::RrcConnectionReestablishmentRequest RrcConnectionReestablishmentRequestHeader::GetMessage () const { LteRrcSap::RrcConnectionReestablishmentRequest msg; msg.ueIdentity = m_ueIdentity; msg.reestablishmentCause = m_reestablishmentCause; return msg; } LteRrcSap::ReestabUeIdentity RrcConnectionReestablishmentRequestHeader::GetUeIdentity () const { return m_ueIdentity; } LteRrcSap::ReestablishmentCause RrcConnectionReestablishmentRequestHeader::GetReestablishmentCause () const { return m_reestablishmentCause; } //////////////////// RrcConnectionReestablishmentHeader class //////////////////////// RrcConnectionReestablishmentHeader::RrcConnectionReestablishmentHeader () { } RrcConnectionReestablishmentHeader::~RrcConnectionReestablishmentHeader () { } void RrcConnectionReestablishmentHeader::PreSerialize () const { m_serializationResult = Buffer (); SerializeDlCcchMessage (0); // Serialize RrcConnectionReestablishment sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize rrc-TransactionIdentifier SerializeInteger (m_rrcTransactionIdentifier,0,3); // Serialize criticalExtensions choice SerializeChoice (2,0,false); // Serialize c1 choice SerializeChoice (8,0,false); // Serialize RRCConnectionReestablishment-r8-IEs sequence // 1 optional field, no extension marker SerializeSequence (std::bitset<1> (0),false); // Serialize radioResourceConfigDedicated SerializeRadioResourceConfigDedicated (m_radioResourceConfigDedicated); // Serialize nextHopChainingCount SerializeInteger (0,0,7); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionReestablishmentHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeDlCcchMessage (bIterator); // Deserialize RrcConnectionReestablishment sequence // 0 optional fields, no extension marker bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize rrc-TransactionIdentifier bIterator = DeserializeInteger (&n,0,3,bIterator); m_rrcTransactionIdentifier = n; // Deserialize criticalExtensions choice int criticalExtensionsChoice; bIterator = DeserializeChoice (2,false,&criticalExtensionsChoice,bIterator); if (criticalExtensionsChoice == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionsChoice == 0) { // Deserialize c1 int c1; bIterator = DeserializeChoice (8,false,&c1,bIterator); if (c1 > 0) { bIterator = DeserializeNull (bIterator); } else if (c1 == 0) { // Deserialize rrcConnectionReestablishment-r8 // 1 optional field std::bitset<1> nonCriticalExtensionPresent; bIterator = DeserializeSequence (&nonCriticalExtensionPresent,false,bIterator); // Deserialize RadioResourceConfigDedicated bIterator = DeserializeRadioResourceConfigDedicated (&m_radioResourceConfigDedicated,bIterator); // Deserialize nextHopChainingCount bIterator = DeserializeInteger (&n,0,7,bIterator); } } return GetSerializedSize (); } void RrcConnectionReestablishmentHeader::Print (std::ostream &os) const { os << "rrcTransactionIdentifier: " << (int)m_rrcTransactionIdentifier << std::endl; os << "RadioResourceConfigDedicated: " << std::endl; RrcAsn1Header::Print (os,m_radioResourceConfigDedicated); } void RrcConnectionReestablishmentHeader::SetMessage (LteRrcSap::RrcConnectionReestablishment msg) { m_rrcTransactionIdentifier = msg.rrcTransactionIdentifier; m_radioResourceConfigDedicated = msg.radioResourceConfigDedicated; m_isDataSerialized = false; } LteRrcSap::RrcConnectionReestablishment RrcConnectionReestablishmentHeader::GetMessage () const { LteRrcSap::RrcConnectionReestablishment msg; msg.rrcTransactionIdentifier = m_rrcTransactionIdentifier; msg.radioResourceConfigDedicated = m_radioResourceConfigDedicated; return msg; } uint8_t RrcConnectionReestablishmentHeader::GetRrcTransactionIdentifier () const { return m_rrcTransactionIdentifier; } LteRrcSap::RadioResourceConfigDedicated RrcConnectionReestablishmentHeader::GetRadioResourceConfigDedicated () const { return m_radioResourceConfigDedicated; } //////////////////// RrcConnectionReestablishmentCompleteHeader class //////////////////////// RrcConnectionReestablishmentCompleteHeader::RrcConnectionReestablishmentCompleteHeader () { } void RrcConnectionReestablishmentCompleteHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize DCCH message SerializeUlDcchMessage (3); // Serialize RrcConnectionReestablishmentComplete sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize rrc-TransactionIdentifier SerializeInteger (m_rrcTransactionIdentifier,0,3); // Serialize criticalExtensions choice SerializeChoice (2,0,false); // Serialize rrcConnectionReestablishmentComplete-r8 sequence // 1 optional field (not present), no extension marker. SerializeSequence (std::bitset<1> (0),false); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionReestablishmentCompleteHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeUlDcchMessage (bIterator); // Deserialize RrcConnectionReestablishmentComplete sequence // 0 optional fields, no extension marker bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize rrc-TransactionIdentifier bIterator = DeserializeInteger (&n,0,3,bIterator); m_rrcTransactionIdentifier = n; // Deserialize criticalExtensions choice int criticalExtensionsChoice; bIterator = DeserializeChoice (2,false,&criticalExtensionsChoice,bIterator); if (criticalExtensionsChoice == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionsChoice == 0) { // Deserialize rrcConnectionReestablishmentComplete-r8 std::bitset<1> opts; bIterator = DeserializeSequence (&opts,false,bIterator); if (opts[0]) { // Deserialize RRCConnectionReestablishmentComplete-v920-IEs // ... } } return GetSerializedSize (); } void RrcConnectionReestablishmentCompleteHeader::Print (std::ostream &os) const { os << "rrcTransactionIdentifier: " << (int)m_rrcTransactionIdentifier << std::endl; } void RrcConnectionReestablishmentCompleteHeader::SetMessage (LteRrcSap::RrcConnectionReestablishmentComplete msg) { m_rrcTransactionIdentifier = msg.rrcTransactionIdentifier; m_isDataSerialized = false; } LteRrcSap::RrcConnectionReestablishmentComplete RrcConnectionReestablishmentCompleteHeader::GetMessage () const { LteRrcSap::RrcConnectionReestablishmentComplete msg; msg.rrcTransactionIdentifier = m_rrcTransactionIdentifier; return msg; } uint8_t RrcConnectionReestablishmentCompleteHeader::GetRrcTransactionIdentifier () const { return m_rrcTransactionIdentifier; } //////////////////// RrcConnectionReestablishmentRejectHeader class //////////////////////// RrcConnectionReestablishmentRejectHeader::RrcConnectionReestablishmentRejectHeader () { } RrcConnectionReestablishmentRejectHeader::~RrcConnectionReestablishmentRejectHeader () { } void RrcConnectionReestablishmentRejectHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize CCCH message SerializeDlCcchMessage (1); // Serialize RrcConnectionReestablishmentReject sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize criticalExtensions choice SerializeChoice (2,0,false); // Serialize RRCConnectionReestablishmentReject-r8-IEs sequence // 1 optional field (not present), no extension marker. SerializeSequence (std::bitset<1> (0),false); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionReestablishmentRejectHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; bIterator = DeserializeDlCcchMessage (bIterator); // Deserialize RrcConnectionReestablishmentReject sequence // 0 optional fields, no extension marker bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize criticalExtensions choice int criticalExtensionsChoice; bIterator = DeserializeChoice (2,false,&criticalExtensionsChoice,bIterator); if (criticalExtensionsChoice == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionsChoice == 0) { // Deserialize rrcConnectionReestablishmentReject-r8 std::bitset<1> opts; bIterator = DeserializeSequence (&opts,false,bIterator); if (opts[0]) { // Deserialize RRCConnectionReestablishmentReject-v8a0-IEs // ... } } return GetSerializedSize (); } void RrcConnectionReestablishmentRejectHeader::Print (std::ostream &os) const { } void RrcConnectionReestablishmentRejectHeader::SetMessage (LteRrcSap::RrcConnectionReestablishmentReject msg) { m_rrcConnectionReestablishmentReject = msg; m_isDataSerialized = false; } LteRrcSap::RrcConnectionReestablishmentReject RrcConnectionReestablishmentRejectHeader::GetMessage () const { return m_rrcConnectionReestablishmentReject; } //////////////////// RrcConnectionReleaseHeader class //////////////////////// RrcConnectionReleaseHeader::RrcConnectionReleaseHeader () { } RrcConnectionReleaseHeader::~RrcConnectionReleaseHeader () { } void RrcConnectionReleaseHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize DCCH message SerializeDlDcchMessage (5); // Serialize RrcConnectionRelease sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize rrc-TransactionIdentifier SerializeInteger (m_rrcConnectionRelease.rrcTransactionIdentifier,0,3); // Serialize criticalExtensions choice SerializeChoice (2,0,false); // Serialize c1 choice SerializeChoice (4,0,false); // Serialize RRCConnectionRelease-r8-IEs sequence // 3 optional field (not present), no extension marker. SerializeSequence (std::bitset<3> (0),false); // Serialize ReleaseCause SerializeEnum (4,1); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionReleaseHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeDlDcchMessage (bIterator); // Deserialize RrcConnectionRelease sequence // 0 optional fields, no extension marker bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize rrc-TransactionIdentifier bIterator = DeserializeInteger (&n,0,3,bIterator); m_rrcConnectionRelease.rrcTransactionIdentifier = n; // Deserialize criticalExtensions choice int criticalExtensionsChoice; bIterator = DeserializeChoice (2,false,&criticalExtensionsChoice,bIterator); if (criticalExtensionsChoice == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionsChoice == 0) { // Deserialize c1 int c1Choice; bIterator = DeserializeChoice (4,false,&c1Choice,bIterator); if (c1Choice == 0) { // Deserialize RRCConnectionRelease-r8-IEs std::bitset<3> opts; bIterator = DeserializeSequence (&opts,false,bIterator); // Deserialize releaseCause bIterator = DeserializeEnum (4,&n,bIterator); if (opts[2]) { // Deserialize redirectedCarrierInfo // ... } if (opts[1]) { // Deserialize idleModeMobilityControlInfo // ... } if (opts[0]) { // Deserialize nonCriticalExtension // ... } } else { bIterator = DeserializeNull (bIterator); } } return GetSerializedSize (); } void RrcConnectionReleaseHeader::Print (std::ostream &os) const { } void RrcConnectionReleaseHeader::SetMessage (LteRrcSap::RrcConnectionRelease msg) { m_rrcConnectionRelease = msg; m_isDataSerialized = false; } LteRrcSap::RrcConnectionRelease RrcConnectionReleaseHeader::GetMessage () const { return m_rrcConnectionRelease; } //////////////////// RrcConnectionRejectHeader class //////////////////////// RrcConnectionRejectHeader::RrcConnectionRejectHeader () { } RrcConnectionRejectHeader::~RrcConnectionRejectHeader () { } void RrcConnectionRejectHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize CCCH message SerializeDlCcchMessage (2); // Serialize RrcConnectionReject sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize criticalExtensions choice SerializeChoice (2,0,false); // Serialize c1 choice SerializeChoice (4,0,false); // Serialize rrcConnectionReject-r8 sequence // 1 optional field (not present), no extension marker. SerializeSequence (std::bitset<1> (0),false); // Serialize waitTime SerializeInteger (m_rrcConnectionReject.waitTime, 1, 16); // Finish serialization FinalizeSerialization (); } uint32_t RrcConnectionRejectHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeDlCcchMessage (bIterator); // Deserialize RrcConnectionReject sequence // 0 optional fields, no extension marker bIterator = DeserializeSequence (&bitset0,false,bIterator); // Deserialize criticalExtensions choice int criticalExtensionsChoice; bIterator = DeserializeChoice (2,false,&criticalExtensionsChoice,bIterator); if (criticalExtensionsChoice == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionsChoice == 0) { // Deserialize c1 choice int c1Choice; bIterator = DeserializeChoice (4,false,&c1Choice,bIterator); if (c1Choice > 0) { bIterator = DeserializeNull (bIterator); } else if (c1Choice == 0) { // Deserialize rrcConnectionReject-r8 std::bitset<1> opts; bIterator = DeserializeSequence (&opts,false,bIterator); bIterator = DeserializeInteger (&n,1,16,bIterator); m_rrcConnectionReject.waitTime = n; if (opts[0]) { // Deserialize RRCConnectionReject-v8a0-IEs // ... } } } return GetSerializedSize (); } void RrcConnectionRejectHeader::Print (std::ostream &os) const { os << "wait time: " << (int)m_rrcConnectionReject.waitTime << std::endl; } void RrcConnectionRejectHeader::SetMessage (LteRrcSap::RrcConnectionReject msg) { m_rrcConnectionReject = msg; m_isDataSerialized = false; } LteRrcSap::RrcConnectionReject RrcConnectionRejectHeader::GetMessage () const { return m_rrcConnectionReject; } //////////////////// MeasurementReportHeader class //////////////////////// MeasurementReportHeader::MeasurementReportHeader () { } MeasurementReportHeader::~MeasurementReportHeader () { } void MeasurementReportHeader::PreSerialize () const { m_serializationResult = Buffer (); // Serialize DCCH message SerializeUlDcchMessage (1); // Serialize MeasurementReport sequence: // no default or optional fields. Extension marker not present. SerializeSequence (std::bitset<0> (),false); // Serialize criticalExtensions choice: // c1 chosen SerializeChoice (2,0,false); // Serialize c1 choice // measurementReport-r8 chosen SerializeChoice (8,0,false); // Serialize MeasurementReport-r8-IEs sequence: // 1 optional fields, not present. Extension marker not present. SerializeSequence (std::bitset<1> (0),false); // Serialize measResults SerializeMeasResults (m_measurementReport.measResults); // Finish serialization FinalizeSerialization (); } uint32_t MeasurementReportHeader::Deserialize (Buffer::Iterator bIterator) { std::bitset<0> bitset0; bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeUlDcchMessage (bIterator); int criticalExtensionsChoice; bIterator = DeserializeChoice (2,false,&criticalExtensionsChoice,bIterator); if (criticalExtensionsChoice == 1) { // Deserialize criticalExtensionsFuture bIterator = DeserializeSequence (&bitset0,false,bIterator); } else if (criticalExtensionsChoice == 0) { // Deserialize c1 int c1Choice; bIterator = DeserializeChoice (8,false,&c1Choice,bIterator); if (c1Choice > 0) { bIterator = DeserializeNull (bIterator); } else { // Deserialize measurementReport-r8 std::bitset<1> isNonCriticalExtensionPresent; bIterator = DeserializeSequence (&isNonCriticalExtensionPresent,false,bIterator); // Deserialize measResults bIterator = DeserializeMeasResults (&m_measurementReport.measResults, bIterator); if (isNonCriticalExtensionPresent[0]) { // Deserialize nonCriticalExtension MeasurementReport-v8a0-IEs // ... } } } return GetSerializedSize (); } void MeasurementReportHeader::Print (std::ostream &os) const { os << "measId = " << (int)m_measurementReport.measResults.measId << std::endl; os << "rsrpResult = " << (int)m_measurementReport.measResults.rsrpResult << std::endl; os << "rsrqResult = " << (int)m_measurementReport.measResults.rsrqResult << std::endl; os << "haveMeasResultNeighCells = " << (int)m_measurementReport.measResults.haveMeasResultNeighCells << std::endl; if (m_measurementReport.measResults.haveMeasResultNeighCells) { std::list<LteRrcSap::MeasResultEutra> measResultListEutra = m_measurementReport.measResults.measResultListEutra; std::list<LteRrcSap::MeasResultEutra>::iterator it = measResultListEutra.begin (); for (; it != measResultListEutra.end (); it++) { os << " physCellId =" << (int) it->physCellId << std::endl; os << " haveCgiInfo =" << it->haveCgiInfo << std::endl; if (it->haveCgiInfo) { os << " plmnIdentity = " << (int) it->cgiInfo.plmnIdentity << std::endl; os << " cellIdentity = " << (int) it->cgiInfo.cellIdentity << std::endl; os << " trackingAreaCode = " << (int) it->cgiInfo.trackingAreaCode << std::endl; os << " havePlmnIdentityList = " << !it->cgiInfo.plmnIdentityList.empty () << std::endl; if (!it->cgiInfo.plmnIdentityList.empty ()) { for (std::list<uint32_t>::iterator it2 = it->cgiInfo.plmnIdentityList.begin (); it2 != it->cgiInfo.plmnIdentityList.end (); it2++) { os << " plmnId : " << *it2 << std::endl; } } } os << " haveRsrpResult =" << it->haveRsrpResult << std::endl; if (it->haveRsrpResult) { os << " rsrpResult =" << (int) it->rsrpResult << std::endl; } os << " haveRsrqResult =" << it->haveRsrqResult << std::endl; if (it->haveRsrqResult) { os << " rsrqResult =" << (int) it->rsrqResult << std::endl; } } } } void MeasurementReportHeader::SetMessage (LteRrcSap::MeasurementReport msg) { m_measurementReport = msg; m_isDataSerialized = false; } LteRrcSap::MeasurementReport MeasurementReportHeader::GetMessage () const { LteRrcSap::MeasurementReport msg; msg = m_measurementReport; return msg; } /////////////////// RrcUlDcchMessage ////////////////////////////////// RrcUlDcchMessage::RrcUlDcchMessage () : RrcAsn1Header () { } RrcUlDcchMessage::~RrcUlDcchMessage () { } uint32_t RrcUlDcchMessage::Deserialize (Buffer::Iterator bIterator) { DeserializeUlDcchMessage (bIterator); return 1; } void RrcUlDcchMessage::Print (std::ostream &os) const { std::cout << "UL DCCH MSG TYPE: " << m_messageType << std::endl; } void RrcUlDcchMessage::PreSerialize () const { SerializeUlDcchMessage (m_messageType); } Buffer::Iterator RrcUlDcchMessage::DeserializeUlDcchMessage (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeChoice (2,false,&n,bIterator); if (n == 1) { // Deserialize messageClassExtension bIterator = DeserializeSequence (&bitset0,false,bIterator); m_messageType = -1; } else if (n == 0) { // Deserialize c1 bIterator = DeserializeChoice (16,false,&m_messageType,bIterator); } return bIterator; } void RrcUlDcchMessage::SerializeUlDcchMessage (int messageType) const { SerializeSequence (std::bitset<0> (),false); // Choose c1 SerializeChoice (2,0,false); // Choose message type SerializeChoice (16,messageType,false); } /////////////////// RrcDlDcchMessage ////////////////////////////////// RrcDlDcchMessage::RrcDlDcchMessage () : RrcAsn1Header () { } RrcDlDcchMessage::~RrcDlDcchMessage () { } uint32_t RrcDlDcchMessage::Deserialize (Buffer::Iterator bIterator) { DeserializeDlDcchMessage (bIterator); return 1; } void RrcDlDcchMessage::Print (std::ostream &os) const { std::cout << "DL DCCH MSG TYPE: " << m_messageType << std::endl; } void RrcDlDcchMessage::PreSerialize () const { SerializeDlDcchMessage (m_messageType); } Buffer::Iterator RrcDlDcchMessage::DeserializeDlDcchMessage (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeChoice (2,false,&n,bIterator); if (n == 1) { // Deserialize messageClassExtension bIterator = DeserializeSequence (&bitset0,false,bIterator); m_messageType = -1; } else if (n == 0) { // Deserialize c1 bIterator = DeserializeChoice (16,false,&m_messageType,bIterator); } return bIterator; } void RrcDlDcchMessage::SerializeDlDcchMessage (int messageType) const { SerializeSequence (std::bitset<0> (),false); // Choose c1 SerializeChoice (2,0,false); // Choose message type SerializeChoice (16,messageType,false); } /////////////////// RrcUlCcchMessage ////////////////////////////////// RrcUlCcchMessage::RrcUlCcchMessage () : RrcAsn1Header () { } RrcUlCcchMessage::~RrcUlCcchMessage () { } uint32_t RrcUlCcchMessage::Deserialize (Buffer::Iterator bIterator) { DeserializeUlCcchMessage (bIterator); return 1; } void RrcUlCcchMessage::Print (std::ostream &os) const { std::cout << "UL CCCH MSG TYPE: " << m_messageType << std::endl; } void RrcUlCcchMessage::PreSerialize () const { SerializeUlCcchMessage (m_messageType); } Buffer::Iterator RrcUlCcchMessage::DeserializeUlCcchMessage (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeChoice (2,false,&n,bIterator); if (n == 1) { // Deserialize messageClassExtension bIterator = DeserializeSequence (&bitset0,false,bIterator); m_messageType = -1; } else if (n == 0) { // Deserialize c1 bIterator = DeserializeChoice (2,false,&m_messageType,bIterator); } return bIterator; } void RrcUlCcchMessage::SerializeUlCcchMessage (int messageType) const { SerializeSequence (std::bitset<0> (),false); // Choose c1 SerializeChoice (2,0,false); // Choose message type SerializeChoice (2,messageType,false); } /////////////////// RrcDlCcchMessage ////////////////////////////////// RrcDlCcchMessage::RrcDlCcchMessage () : RrcAsn1Header () { } RrcDlCcchMessage::~RrcDlCcchMessage () { } uint32_t RrcDlCcchMessage::Deserialize (Buffer::Iterator bIterator) { DeserializeDlCcchMessage (bIterator); return 1; } void RrcDlCcchMessage::Print (std::ostream &os) const { std::cout << "DL CCCH MSG TYPE: " << m_messageType << std::endl; } void RrcDlCcchMessage::PreSerialize () const { SerializeDlCcchMessage (m_messageType); } Buffer::Iterator RrcDlCcchMessage::DeserializeDlCcchMessage (Buffer::Iterator bIterator) { std::bitset<0> bitset0; int n; bIterator = DeserializeSequence (&bitset0,false,bIterator); bIterator = DeserializeChoice (2,false,&n,bIterator); if (n == 1) { // Deserialize messageClassExtension bIterator = DeserializeSequence (&bitset0,false,bIterator); m_messageType = -1; } else if (n == 0) { // Deserialize c1 bIterator = DeserializeChoice (4,false,&m_messageType,bIterator); } return bIterator; } void RrcDlCcchMessage::SerializeDlCcchMessage (int messageType) const { SerializeSequence (std::bitset<0> (),false); // Choose c1 SerializeChoice (2,0,false); // Choose message type SerializeChoice (4,messageType,false); } } // namespace ns3
rathoresrikant/Implementation-of-Curvy-RED-in-ns-3
src/lte/model/lte-rrc-header.cc
C++
gpl-2.0
237,854
/* * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This code is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * only, as published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 16 Network Circle, Menlo * Park, CA 94025 or visit www.sun.com if you need additional * information or have any questions. */ package com.sun.cldc.util.j2me; import java.util.*; /** * This class is an implementation of the subsetted * CLDC 1.1 Calendar class. * * @see java.util.Calendar * @see java.util.TimeZone */ public class CalendarImpl extends Calendar { /* ERA */ private static final int BC = 0; private static final int AD = 1; /* January 1, year 1 (Gregorian) */ private static final int JAN_1_1_JULIAN_DAY = 1721426; /* January 1, 1970 (Gregorian) */ private static final int EPOCH_JULIAN_DAY = 2440588; /* 0-based, for day-in-year */ private static final int NUM_DAYS[] = {0,31,59,90,120,151,181,212,243,273,304,334}; /* 0-based, for day-in-year */ private static final int LEAP_NUM_DAYS[] = {0,31,60,91,121,152,182,213,244,274,305,335}; /** * Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit * into ints, they must be longs in order to prevent arithmetic overflow * when performing (bug 4173516). */ private static final int ONE_SECOND = 1000; private static final int ONE_MINUTE = 60*ONE_SECOND; private static final int ONE_HOUR = 60*ONE_MINUTE; private static final long ONE_DAY = 24*ONE_HOUR; private static final long ONE_WEEK = 7*ONE_DAY; /** * The point at which the Gregorian calendar rules are used, measured in * milliseconds from the standard epoch. Default is October 15, 1582 * (Gregorian) 00:00:00 UTC or -12219292800000L. For this value, October 4, * 1582 (Julian) is followed by October 15, 1582 (Gregorian). This * corresponds to Julian day number 2299161. */ private static final long gregorianCutover = -12219292800000L; /** * The year of the gregorianCutover, with 0 representing * 1 BC, -1 representing 2 BC, etc. */ private static final int gregorianCutoverYear = 1582; public CalendarImpl() { super(); } /** * Converts UTC as milliseconds to time field values. */ protected void computeFields() { int rawOffset = getTimeZone().getRawOffset(); long localMillis = time + rawOffset; // Check for very extreme values -- millis near Long.MIN_VALUE or // Long.MAX_VALUE. For these values, adding the zone offset can push // the millis past MAX_VALUE to MIN_VALUE, or vice versa. This produces // the undesirable effect that the time can wrap around at the ends, // yielding, for example, a Date(Long.MAX_VALUE) with a big BC year // (should be AD). Handle this by pinning such values to Long.MIN_VALUE // or Long.MAX_VALUE. - liu 8/11/98 bug 4149677 if (time > 0 && localMillis < 0 && rawOffset > 0) { localMillis = Long.MAX_VALUE; } else if (time < 0 && localMillis > 0 && rawOffset < 0) { localMillis = Long.MIN_VALUE; } // Time to fields takes the wall millis (Standard or DST). timeToFields(localMillis); long ndays = (localMillis / ONE_DAY); int millisInDay = (int)(localMillis - (ndays * ONE_DAY)); if (millisInDay < 0) millisInDay += ONE_DAY; // Call getOffset() to get the TimeZone offset. // The millisInDay value must be standard local millis. int dstOffset = getTimeZone().getOffset(AD, this.fields[YEAR], this.fields[MONTH], this.fields[DATE], this.fields[DAY_OF_WEEK], millisInDay) - rawOffset; // Adjust our millisInDay for DST, if necessary. millisInDay += dstOffset; // If DST has pushed us into the next day, // we must call timeToFields() again. // This happens in DST between 12:00 am and 1:00 am every day. // The call to timeToFields() will give the wrong day, // since the Standard time is in the previous day if (millisInDay >= ONE_DAY) { long dstMillis = localMillis + dstOffset; millisInDay -= ONE_DAY; // As above, check for and pin extreme values if (localMillis > 0 && dstMillis < 0 && dstOffset > 0) { dstMillis = Long.MAX_VALUE; } else if (localMillis < 0 && dstMillis > 0 && dstOffset < 0) { dstMillis = Long.MIN_VALUE; } timeToFields(dstMillis); } // Fill in all time-related fields based on millisInDay. // so as not to perturb flags. this.fields[MILLISECOND] = millisInDay % 1000; millisInDay /= 1000; this.fields[SECOND] = millisInDay % 60; millisInDay /= 60; this.fields[MINUTE] = millisInDay % 60; millisInDay /= 60; this.fields[HOUR_OF_DAY] = millisInDay; this.fields[AM_PM] = millisInDay / 12; this.fields[HOUR] = millisInDay % 12; } /** * Convert the time as milliseconds to the date fields. Millis must be * given as local wall millis to get the correct local day. For example, * if it is 11:30 pm Standard, and DST is in effect, the correct DST millis * must be passed in to get the right date. * <p> * Fields that are completed by this method: YEAR, MONTH, DATE, DAY_OF_WEEK. * @param theTime the time in wall millis (either Standard or DST), * whichever is in effect */ private void timeToFields(long theTime) { int dayOfYear, rawYear; boolean isLeap; // Compute the year, month, and day of month from the given millis if (theTime >= gregorianCutover) { // The Gregorian epoch day is zero for Monday January 1, year 1. long gregorianEpochDay = millisToJulianDay(theTime) - JAN_1_1_JULIAN_DAY; // Here we convert from the day number to the multiple radix // representation. We use 400-year, 100-year, and 4-year cycles. // For example, the 4-year cycle has 4 years + 1 leap day; giving // 1461 == 365*4 + 1 days. int[] rem = new int[1]; // 400-year cycle length int n400 = floorDivide(gregorianEpochDay, 146097, rem); // 100-year cycle length int n100 = floorDivide(rem[0], 36524, rem); // 4-year cycle length int n4 = floorDivide(rem[0], 1461, rem); int n1 = floorDivide(rem[0], 365, rem); rawYear = 400*n400 + 100*n100 + 4*n4 + n1; // zero-based day of year dayOfYear = rem[0]; // Dec 31 at end of 4- or 400-yr cycle if (n100 == 4 || n1 == 4) { dayOfYear = 365; } else { ++rawYear; } // equiv. to (rawYear%4 == 0) isLeap = ((rawYear&0x3) == 0) && (rawYear%100 != 0 || rawYear%400 == 0); // Gregorian day zero is a Monday this.fields[DAY_OF_WEEK] = (int)((gregorianEpochDay+1) % 7); } else { // The Julian epoch day (not the same as Julian Day) // is zero on Saturday December 30, 0 (Gregorian). long julianEpochDay = millisToJulianDay(theTime) - (JAN_1_1_JULIAN_DAY - 2); rawYear = (int) floorDivide(4*julianEpochDay + 1464, 1461); // Compute the Julian calendar day number for January 1, year long january1 = 365*(rawYear-1) + floorDivide(rawYear-1, 4); dayOfYear = (int)(julianEpochDay - january1); // 0-based // Julian leap years occurred historically every 4 years starting // with 8 AD. Before 8 AD the spacing is irregular; every 3 years // from 45 BC to 9 BC, and then none until 8 AD. However, we don't // implement this historical detail; instead, we implement the // computationally cleaner proleptic calendar, which assumes // consistent 4-year cycles throughout time. // equiv. to (rawYear%4 == 0) isLeap = ((rawYear&0x3) == 0); // Julian calendar day zero is a Saturday this.fields[DAY_OF_WEEK] = (int)((julianEpochDay-1) % 7); } // Common Julian/Gregorian calculation int correction = 0; // zero-based DOY for March 1 int march1 = isLeap ? 60 : 59; if (dayOfYear >= march1) correction = isLeap ? 1 : 2; // zero-based month int month_field = (12 * (dayOfYear + correction) + 6) / 367; // one-based DOM int date_field = dayOfYear - (isLeap ? LEAP_NUM_DAYS[month_field] : NUM_DAYS[month_field]) + 1; // Normalize day of week this.fields[DAY_OF_WEEK] += (this.fields[DAY_OF_WEEK] < 0) ? (SUNDAY+7) : SUNDAY; this.fields[YEAR] = rawYear; // If year is < 1 we are in BC if (this.fields[YEAR] < 1) { this.fields[YEAR] = 1 - this.fields[YEAR]; } // 0-based this.fields[MONTH] = month_field + JANUARY; this.fields[DATE] = date_field; } /* * The following two static arrays are used privately by the * <code>toString(Calendar calendar)</code> function below. */ static String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; static String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; /** * Converts this <code>Date</code> object to a <code>String</code> * of the form: * <blockquote><pre> * dow mon dd hh:mm:ss zzz yyyy</pre></blockquote> * where:<ul> * <li><tt>dow</tt> is the day of the week (<tt>Sun, Mon, Tue, Wed, * Thu, Fri, Sat</tt>). * <li><tt>mon</tt> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun, * Jul, Aug, Sep, Oct, Nov, Dec</tt>). * <li><tt>dd</tt> is the day of the month (<tt>01</tt> through * <tt>31</tt>), as two decimal digits. * <li><tt>hh</tt> is the hour of the day (<tt>00</tt> through * <tt>23</tt>), as two decimal digits. * <li><tt>mm</tt> is the minute within the hour (<tt>00</tt> through * <tt>59</tt>), as two decimal digits. * <li><tt>ss</tt> is the second within the minute (<tt>00</tt> through * <tt>61</tt>, as two decimal digits. * <li><tt>zzz</tt> is the time zone (and may reflect daylight savings * time). If time zone information is not available, * then <tt>zzz</tt> is empty - that is, it consists * of no characters at all. * <li><tt>yyyy</tt> is the year, as four decimal digits. * </ul> * * @return a string representation of this date. */ public static String toString(Calendar calendar) { // Printing in the absence of a Calendar // implementation class is not supported if (calendar == null) { return "Thu Jan 01 00:00:00 UTC 1970"; } int dow = calendar.get(Calendar.DAY_OF_WEEK); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); int year = calendar.get(Calendar.YEAR); String yr = Integer.toString(year); TimeZone zone = calendar.getTimeZone(); String zoneID = zone.getID(); if (zoneID == null) zoneID = ""; // The total size of the string buffer // 3+1+3+1+2+1+2+1+2+1+2+1+zoneID.length+1+yr.length // = 21 + zoneID.length + yr.length StringBuffer sb = new StringBuffer(25 + zoneID.length() + yr.length()); sb.append(days[dow-1]).append(' '); sb.append(months[month]).append(' '); appendTwoDigits(sb, day).append(' '); appendTwoDigits(sb, hour_of_day).append(':'); appendTwoDigits(sb, minute).append(':'); appendTwoDigits(sb, seconds).append(' '); if (zoneID.length() > 0) sb.append(zoneID).append(' '); appendFourDigits(sb, year); return sb.toString(); } /** * Converts this <code>Date</code> object to a <code>String</code>. * The output format is as follows: * <blockquote><pre>yyyy MM dd hh mm ss +zzzz</pre></blockquote> * where:<ul> * <li><dd>yyyy</dd> is the year, as four decimal digits. * Year values larger than <dd>9999</dd> will be truncated * to <dd>9999</dd>. * <li><dd>MM</dd> is the month (<dd>01</dd> through <dd>12</dd>), * as two decimal digits. * <li><dd>dd</dd> is the day of the month (<dd>01</dd> through * <dd>31</dd>), as two decimal digits. * <li><dd>hh</dd> is the hour of the day (<dd>00</dd> through * <dd>23</dd>), as two decimal digits. * <li><dd>mm</dd> is the minute within the hour (<dd>00</dd> * through <dd>59</dd>), as two decimal digits. * <li><dd>ss</dd> is the second within the minute (<dd>00</dd> * through <dd>59</dd>), as two decimal digits. * <li><dd>zzzz</dd> is the time zone offset in hours and minutes * (four decimal digits <dd>"hhmm"</dd>) relative to GMT, * preceded by a "+" or "-" character (<dd>-1200</dd> * through <dd>+1200</dd>). * For instance, Pacific Standard Time zone is printed * as <dd>-0800</dd>. GMT is printed as <dd>+0000</dd>. * </ul> * * @return a string representation of this date. */ public static String toISO8601String(Calendar calendar) { // Printing in the absence of a Calendar // implementation class is not supported if (calendar == null) { return "0000 00 00 00 00 00 +0000"; } int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); String yr = Integer.toString(year); // The total size of the string buffer // yr.length+1+2+1+2+1+2+1+2+1+2+1+5 = 25 + yr.length StringBuffer sb = new StringBuffer(25 + yr.length()); appendFourDigits(sb, year).append(' '); appendTwoDigits(sb, month).append(' '); appendTwoDigits(sb, day).append(' '); appendTwoDigits(sb, hour_of_day).append(' '); appendTwoDigits(sb, minute).append(' '); appendTwoDigits(sb, seconds).append(' '); // TimeZone offset is represented in milliseconds. // Convert the offset to minutes: TimeZone t = calendar.getTimeZone(); int zoneOffsetInMinutes = t.getRawOffset() / 1000 / 60; if (zoneOffsetInMinutes < 0) { zoneOffsetInMinutes = Math.abs(zoneOffsetInMinutes); sb.append('-'); } else { sb.append('+'); } int zoneHours = zoneOffsetInMinutes / 60; int zoneMinutes = zoneOffsetInMinutes % 60; appendTwoDigits(sb, zoneHours); appendTwoDigits(sb, zoneMinutes); return sb.toString(); } private static StringBuffer appendFourDigits(StringBuffer sb, int number) { if (number >= 0 && number < 1000) { sb.append('0'); if (number < 100) { sb.append('0'); } if (number < 10) { sb.append('0'); } } return sb.append(number); } private static StringBuffer appendTwoDigits(StringBuffer sb, int number) { if (number < 10) { sb.append('0'); } return sb.append(number); } ///////////////////////////// // Fields => Time computation ///////////////////////////// /** * Converts time field values to UTC as milliseconds. * @exception IllegalArgumentException if any fields are invalid. */ protected void computeTime() { correctTime(); // This function takes advantage of the fact that unset fields in // the time field list have a value of zero. // First, use the year to determine whether to use the Gregorian or the // Julian calendar. If the year is not the year of the cutover, this // computation will be correct. But if the year is the cutover year, // this may be incorrect. In that case, assume the Gregorian calendar, // make the computation, and then recompute if the resultant millis // indicate the wrong calendar has been assumed. // A date such as Oct. 10, 1582 does not exist in a Gregorian calendar // with the default changeover of Oct. 15, 1582, since in such a // calendar Oct. 4 (Julian) is followed by Oct. 15 (Gregorian). This // algorithm will interpret such a date using the Julian calendar, // yielding Oct. 20, 1582 (Gregorian). int year = this.fields[YEAR]; boolean isGregorian = year >= gregorianCutoverYear; long julianDay = calculateJulianDay(isGregorian, year); long millis = julianDayToMillis(julianDay); // The following check handles portions of the cutover year BEFORE the // cutover itself happens. The check for the julianDate number is for a // rare case; it's a hardcoded number, but it's efficient. The given // Julian day number corresponds to Dec 3, 292269055 BC, which // corresponds to millis near Long.MIN_VALUE. The need for the check // arises because for extremely negative Julian day numbers, the millis // actually overflow to be positive values. Without the check, the // initial date is interpreted with the Gregorian calendar, even when // the cutover doesn't warrant it. if (isGregorian != (millis >= gregorianCutover) && julianDay != -106749550580L) { // See above julianDay = calculateJulianDay(!isGregorian, year); millis = julianDayToMillis(julianDay); } // Do the time portion of the conversion. int millisInDay = 0; // Hours // Don't normalize here; let overflow bump into the next period. // This is consistent with how we handle other fields. millisInDay += this.fields[HOUR_OF_DAY]; millisInDay *= 60; // now get minutes millisInDay += this.fields[MINUTE]; millisInDay *= 60; // now get seconds millisInDay += this.fields[SECOND]; millisInDay *= 1000; // now get millis millisInDay += this.fields[MILLISECOND]; // Compute the time zone offset and DST offset. There are two potential // ambiguities here. We'll assume a 2:00 am (wall time) switchover time // for discussion purposes here. // 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am // can be in standard or in DST depending. However, 2:00 am is an invalid // representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST). // We assume standard time. // 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am // can be in standard or DST. Both are valid representations (the rep // jumps from 1:59:59 DST to 1:00:00 Std). // Again, we assume standard time. // We use the TimeZone object to get the zone offset int zoneOffset = getTimeZone().getRawOffset(); // Now add date and millisInDay together, to make millis contain local wall // millis, with no zone or DST adjustments millis += millisInDay; // Normalize the millisInDay to 0..ONE_DAY-1. If the millis is out // of range, then we must call timeToFields() to recompute our // fields. int[] normalizedMillisInDay = new int[1]; floorDivide(millis, (int)ONE_DAY, normalizedMillisInDay); // We need to have the month, the day, and the day of the week. // Calling timeToFields will compute the MONTH and DATE fields. // // It's tempting to try to use DAY_OF_WEEK here, if it // is set, but we CAN'T. Even if it's set, it might have // been set wrong by the user. We should rely only on // the Julian day number, which has been computed correctly // using the disambiguation algorithm above. [LIU] int dow = julianDayToDayOfWeek(julianDay); // It's tempting to try to use DAY_OF_WEEK here, if it // is set, but we CAN'T. Even if it's set, it might have // been set wrong by the user. We should rely only on // the Julian day number, which has been computed correctly // using the disambiguation algorithm above. [LIU] int dstOffset = getTimeZone().getOffset(AD, this.fields[YEAR], this.fields[MONTH], this.fields[DATE], dow, normalizedMillisInDay[0]) - zoneOffset; // Note: Because we pass in wall millisInDay, rather than // standard millisInDay, we interpret "1:00 am" on the day // of cessation of DST as "1:00 am Std" (assuming the time // of cessation is 2:00 am). // Store our final computed GMT time, with timezone adjustments. time = millis - zoneOffset - dstOffset; } /** * Compute the Julian day number under either the Gregorian or the * Julian calendar, using the given year and the remaining fields. * @param isGregorian if true, use the Gregorian calendar * @param year the adjusted year number, with 0 indicating the * year 1 BC, -1 indicating 2 BC, etc. * @return the Julian day number */ private long calculateJulianDay(boolean isGregorian, int year) { int month = 0; month = this.fields[MONTH] - JANUARY; // If the month is out of range, adjust it into range if (month < 0 || month > 11) { int[] rem = new int[1]; year += floorDivide(month, 12, rem); month = rem[0]; } boolean isLeap = year%4 == 0; long julianDay = 365L*(year - 1) + floorDivide((year - 1), 4) + (JAN_1_1_JULIAN_DAY - 3); if (isGregorian) { isLeap = isLeap && ((year%100 != 0) || (year%400 == 0)); // Add 2 because Gregorian calendar starts 2 days after Julian calendar julianDay += floorDivide((year - 1), 400) - floorDivide((year - 1), 100) + 2; } // At this point julianDay is the 0-based day BEFORE the first day of // January 1, year 1 of the given calendar. If julianDay == 0, it // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian // or Gregorian). julianDay += isLeap ? LEAP_NUM_DAYS[month] : NUM_DAYS[month]; julianDay += this.fields[DATE]; return julianDay; } /** * Validates the field values for HOUR_OF_DAY, AM_PM and HOUR * The calendar will give preference in the following order * HOUR_OF_DAY, AM_PM, HOUR */ private void correctTime() { int value; if (isSet[HOUR_OF_DAY]) { value = this.fields[HOUR_OF_DAY] % 24; this.fields[HOUR_OF_DAY] = value; this.fields[AM_PM] = (value < 12) ? AM : PM; this.isSet[HOUR_OF_DAY] = false; return; } if(isSet[AM_PM]) { // Determines AM PM with the 24 hour clock // This prevents the user from inputing an invalid one. if (this.fields[AM_PM] != AM && this.fields[AM_PM] != PM) { value = this.fields[HOUR_OF_DAY]; this.fields[AM_PM] = (value < 12) ? AM : PM; } this.isSet[AM_PM] = false; } if (isSet[HOUR]) { value = this.fields[HOUR]; if (value > 12) { this.fields[HOUR_OF_DAY] = (value % 12) + 12; this.fields[HOUR] = value % 12; this.fields[AM_PM] = PM; } else { if (this.fields[AM_PM] == PM) { this.fields[HOUR_OF_DAY] = value + 12; } else { this.fields[HOUR_OF_DAY] = value; } } this.isSet[HOUR] = false; } } ///////////////// // Implementation ///////////////// /** * Converts time as milliseconds to Julian day. * @param millis the given milliseconds. * @return the Julian day number. */ private static long millisToJulianDay(long millis) { return EPOCH_JULIAN_DAY + floorDivide(millis, ONE_DAY); } /** * Converts Julian day to time as milliseconds. * @param julian the given Julian day number. * @return time as milliseconds. */ private static long julianDayToMillis(long julian) { return (julian - EPOCH_JULIAN_DAY) * ONE_DAY; } private static int julianDayToDayOfWeek(long julian) { // If julian is negative, then julian%7 will be negative, so we adjust // accordingly. We add 1 because Julian day 0 is Monday. int dayOfWeek = (int)((julian + 1) % 7); return dayOfWeek + ((dayOfWeek < 0) ? (7 + SUNDAY) : SUNDAY); } /** * Divide two long integers, returning the floor of the quotient. * <p> * Unlike the built-in division, this is mathematically well-behaved. * E.g., <code>-1/4</code> => 0 * but <code>floorDivide(-1,4)</code> => -1. * @param numerator the numerator * @param denominator a divisor which must be > 0 * @return the floor of the quotient. */ public static long floorDivide(long numerator, long denominator) { // We do this computation in order to handle // a numerator of Long.MIN_VALUE correctly return (numerator >= 0) ? numerator / denominator : ((numerator + 1) / denominator) - 1; } /** * Divide two integers, returning the floor of the quotient. * <p> * Unlike the built-in division, this is mathematically well-behaved. * E.g., <code>-1/4</code> => 0 * but <code>floorDivide(-1,4)</code> => -1. * @param numerator the numerator * @param denominator a divisor which must be > 0 * @return the floor of the quotient. */ private static int floorDivide(int numerator, int denominator) { // We do this computation in order to handle // a numerator of Integer.MIN_VALUE correctly return (numerator >= 0) ? numerator / denominator : ((numerator + 1) / denominator) - 1; } /** * Divide two integers, returning the floor of the quotient, and * the modulus remainder. * <p> * Unlike the built-in division, this is mathematically well-behaved. * E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1, * but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3. * @param numerator the numerator * @param denominator a divisor which must be > 0 * @param remainder an array of at least one element in which the value * <code>numerator mod denominator</code> is returned. Unlike <code>numerator * % denominator</code>, this will always be non-negative. * @return the floor of the quotient. */ private static int floorDivide(int numerator, int denominator, int[] remainder) { if (numerator >= 0) { remainder[0] = numerator % denominator; return numerator / denominator; } int quotient = ((numerator + 1) / denominator) - 1; remainder[0] = numerator - (quotient * denominator); return quotient; } /** * Divide two integers, returning the floor of the quotient, and * the modulus remainder. * <p> * Unlike the built-in division, this is mathematically well-behaved. * E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1, * but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3. * @param numerator the numerator * @param denominator a divisor which must be > 0 * @param remainder an array of at least one element in which the value * <code>numerator mod denominator</code> is returned. Unlike <code>numerator * % denominator</code>, this will always be non-negative. * @return the floor of the quotient. */ private static int floorDivide(long numerator, int denominator, int[] remainder) { if (numerator >= 0) { remainder[0] = (int)(numerator % denominator); return (int)(numerator / denominator); } int quotient = (int)(((numerator + 1) / denominator) - 1); remainder[0] = (int)(numerator - (quotient * denominator)); return quotient; } }
wufucious/moped
squawk/cldc/src/com/sun/cldc/util/j2me/CalendarImpl.java
Java
gpl-2.0
30,363
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # (c) 2017 Red Hat Inc. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from contextlib import contextmanager from xml.etree.ElementTree import Element, SubElement, fromstring, tostring from ansible.module_utils.connection import exec_command NS_MAP = {'nc': "urn:ietf:params:xml:ns:netconf:base:1.0"} def send_request(module, obj, check_rc=True): request = tostring(obj) rc, out, err = exec_command(module, request) if rc != 0 and check_rc: error_root = fromstring(err) fake_parent = Element('root') fake_parent.append(error_root) error_list = fake_parent.findall('.//nc:rpc-error', NS_MAP) if not error_list: module.fail_json(msg=str(err)) warnings = [] for rpc_error in error_list: message = rpc_error.find('./nc:error-message', NS_MAP).text severity = rpc_error.find('./nc:error-severity', NS_MAP).text if severity == 'warning': warnings.append(message) else: module.fail_json(msg=str(err)) return warnings return fromstring(out) def children(root, iterable): for item in iterable: try: ele = SubElement(ele, item) except NameError: ele = SubElement(root, item) def lock(module, target='candidate'): obj = Element('lock') children(obj, ('target', target)) return send_request(module, obj) def unlock(module, target='candidate'): obj = Element('unlock') children(obj, ('target', target)) return send_request(module, obj) def commit(module): return send_request(module, Element('commit')) def discard_changes(module): return send_request(module, Element('discard-changes')) def validate(module): obj = Element('validate') children(obj, ('source', 'candidate')) return send_request(module, obj) def get_config(module, source='running', filter=None): obj = Element('get-config') children(obj, ('source', source)) children(obj, ('filter', filter)) return send_request(module, obj) @contextmanager def locked_config(module): try: lock(module) yield finally: unlock(module)
tux-00/ansible
lib/ansible/module_utils/netconf.py
Python
gpl-3.0
3,772
require 'active_support/core_ext/array' require 'active_support/core_ext/hash/except' require 'active_support/core_ext/kernel/singleton_class' require 'active_support/core_ext/object/blank' module ActiveRecord # = Active Record Named \Scopes module NamedScope extend ActiveSupport::Concern module ClassMethods # Returns an anonymous \scope. # # posts = Post.scoped # posts.size # Fires "select count(*) from posts" and returns the count # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects # # fruits = Fruit.scoped # fruits = fruits.where(:colour => 'red') if options[:red_only] # fruits = fruits.limit(10) if limited? # # Anonymous \scopes tend to be useful when procedurally generating complex # queries, where passing intermediate values (\scopes) around as first-class # objects is convenient. # # You can define a \scope that applies to all finders using # ActiveRecord::Base.default_scope. def scoped(options = nil) if options scoped.apply_finder_options(options) else current_scoped_methods ? relation.merge(current_scoped_methods) : relation.clone end end def scopes read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {}) end # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query, # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>. # # class Shirt < ActiveRecord::Base # scope :red, where(:color => 'red') # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) # end # # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. # # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance, # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>. # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable; # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> # all behave as if Shirt.red really was an Array. # # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce # all shirts that are both red and dry clean only. # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> # returns the number of garments for which these criteria obtain. Similarly with # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. # # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If, # # class Person < ActiveRecord::Base # has_many :shirts # end # # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean # only shirts. # # Named \scopes can also be procedural: # # class Shirt < ActiveRecord::Base # scope :colored, lambda {|color| where(:color => color) } # end # # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. # # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: # # class Shirt < ActiveRecord::Base # scope :red, where(:color => 'red') do # def dom_id # 'red_shirts' # end # end # end # # Scopes can also be used while creating/building a record. # # class Article < ActiveRecord::Base # scope :published, where(:published => true) # end # # Article.published.new.published # => true # Article.published.create.published # => true def scope(name, scope_options = {}, &block) name = name.to_sym valid_scope_name?(name) extension = Module.new(&block) if block_given? scopes[name] = lambda do |*args| options = scope_options.is_a?(Proc) ? scope_options.call(*args) : scope_options relation = if options.is_a?(Hash) scoped.apply_finder_options(options) elsif options scoped.merge(options) else scoped end extension ? relation.extending(extension) : relation end singleton_class.send(:redefine_method, name, &scopes[name]) end def named_scope(*args, &block) ActiveSupport::Deprecation.warn("Base.named_scope has been deprecated, please use Base.scope instead", caller) scope(*args, &block) end protected def valid_scope_name?(name) if !scopes[name] && respond_to?(name, true) logger.warn "Creating scope :#{name}. " \ "Overwriting existing method #{self.name}.#{name}." end end end end end
mzemel/kpsu.org
vendor/gems/ruby/1.8/gems/activerecord-3.0.3/lib/active_record/named_scope.rb
Ruby
gpl-3.0
5,522
// ******* // This is an internal file of the IMMERSED BOUNDARY implementation // It should not be included by any main Espresso routines // Functions to be exported for Espresso are in ibm_main.hpp #include "config.hpp" #ifdef IMMERSED_BOUNDARY #include <mpi.h> #include "cells.hpp" #include "grid.hpp" #include "communication.hpp" #include "particle_data.hpp" #include "integrate.hpp" #include "immersed_boundary/ibm_cuda_interface.hpp" /// MPI tags for sending velocities and receiving particles #define REQ_CUDAIBMSENDVEL 0xcc03 #define REQ_CUDAIBMGETPART 0xcc04 // Variables for communication IBM_CUDA_ParticleDataInput *IBM_ParticleDataInput_host = NULL; IBM_CUDA_ParticleDataOutput *IBM_ParticleDataOutput_host = NULL; /***************** IBM_cuda_mpi_get_particles Gather particle positions on the master node in order to communicate them to GPU We transfer all particles (real and virtual), but acutally we would only need the virtual ones Room for improvement... *****************/ void IBM_cuda_mpi_get_particles_slave(); // Analogous to the usual cuda_mpi_get_particles function void IBM_cuda_mpi_get_particles() { int g, pnode; Cell *cell; int c; MPI_Status status; int *sizes = (int*) Utils::malloc(sizeof(int)*n_nodes); int n_part = cells_get_n_particles(); /* first collect number of particles on each node */ MPI_Gather(&n_part, 1, MPI_INT, sizes, 1, MPI_INT, 0, comm_cart); if(this_node > 0){ /* call slave functions to provide the slave datas */ IBM_cuda_mpi_get_particles_slave(); } else { /* master: fetch particle informations into 'result' */ g = 0; for (pnode = 0; pnode < n_nodes; pnode++) { if (sizes[pnode] > 0) { if (pnode == 0) { for (c = 0; c < local_cells.n; c++) { Particle *part; int npart; int dummy[3] = {0,0,0}; double pos[3]; cell = local_cells.cell[c]; part = cell->part; npart = cell->n; for (int i=0;i<npart;i++) { memmove(pos, part[i].r.p, 3*sizeof(double)); fold_position(pos, dummy); IBM_ParticleDataInput_host[i+g].pos[0] = (float)pos[0]; IBM_ParticleDataInput_host[i+g].pos[1] = (float)pos[1]; IBM_ParticleDataInput_host[i+g].pos[2] = (float)pos[2]; IBM_ParticleDataInput_host[i+g].f[0] = (float)part[i].f.f[0]; IBM_ParticleDataInput_host[i+g].f[1] = (float)part[i].f.f[1]; IBM_ParticleDataInput_host[i+g].f[2] = (float)part[i].f.f[2]; IBM_ParticleDataInput_host[i+g].isVirtual = part[i].p.isVirtual; } g += npart; } } else { MPI_Recv(&IBM_ParticleDataInput_host[g], sizes[pnode]*sizeof(IBM_CUDA_ParticleDataInput), MPI_BYTE, pnode, REQ_CUDAIBMGETPART, comm_cart, &status); g += sizes[pnode]; } } } } COMM_TRACE(fprintf(stderr, "%d: finished get\n", this_node)); free(sizes); } void IBM_cuda_mpi_get_particles_slave() { int n_part; int g; IBM_CUDA_ParticleDataInput *particle_input_sl; Cell *cell; int c, i; n_part = cells_get_n_particles(); COMM_TRACE(fprintf(stderr, "%d: get_particles_slave, %d particles\n", this_node, n_part)); if (n_part > 0) { /* get (unsorted) particle informations as an array of type 'particle' */ /* then get the particle information */ // particle_data_host_sl = (IBM_CUDA_ParticleDataInput*) Utils::malloc(n_part*sizeof(IBM_CUDA_ParticleData)); particle_input_sl = new IBM_CUDA_ParticleDataInput[n_part]; g = 0; for (c = 0; c < local_cells.n; c++) { Particle *part; int npart; int dummy[3] = {0,0,0}; double pos[3]; cell = local_cells.cell[c]; part = cell->part; npart = cell->n; for (i=0;i<npart;i++) { memmove(pos, part[i].r.p, 3*sizeof(double)); fold_position(pos, dummy); particle_input_sl[i+g].pos[0] = (float)pos[0]; particle_input_sl[i+g].pos[1] = (float)pos[1]; particle_input_sl[i+g].pos[2] = (float)pos[2]; particle_input_sl[i+g].f[0] = (float)part[i].f.f[0]; particle_input_sl[i+g].f[1] = (float)part[i].f.f[1]; particle_input_sl[i+g].f[2] = (float)part[i].f.f[2]; particle_input_sl[i+g].isVirtual = part[i].p.isVirtual; } g+=npart; } /* and send it back to the master node */ MPI_Send(particle_input_sl, n_part*sizeof(IBM_CUDA_ParticleDataInput), MPI_BYTE, 0, REQ_CUDAIBMGETPART, comm_cart); delete []particle_input_sl; } } /***************** IBM_cuda_mpi_send_velocities Particle velocities have been communicated from GPU, now transmit to all nodes ******************/ // Analogous to cuda_mpi_send_forces void IBM_cuda_mpi_send_velocities_slave(); void IBM_cuda_mpi_send_velocities() { int n_part; int g, pnode; Cell *cell; int c; int *sizes; sizes = (int *) Utils::malloc(sizeof(int)*n_nodes); n_part = cells_get_n_particles(); /* first collect number of particles on each node */ MPI_Gather(&n_part, 1, MPI_INT, sizes, 1, MPI_INT, 0, comm_cart); /* call slave functions to provide the slave datas */ if(this_node > 0) { IBM_cuda_mpi_send_velocities_slave(); } else{ /* fetch particle informations into 'result' */ g = 0; for (pnode = 0; pnode < n_nodes; pnode++) { if (sizes[pnode] > 0) { if (pnode == 0) { for (c = 0; c < local_cells.n; c++) { int npart; cell = local_cells.cell[c]; npart = cell->n; for (int i=0;i<npart;i++) { if ( cell->part[i].p.isVirtual ) { cell->part[i].m.v[0] = (double)IBM_ParticleDataOutput_host[(i+g)].v[0]; cell->part[i].m.v[1] = (double)IBM_ParticleDataOutput_host[(i+g)].v[1]; cell->part[i].m.v[2] = (double)IBM_ParticleDataOutput_host[(i+g)].v[2]; } } g += npart; } } else { /* and send it back to the slave node */ MPI_Send(&IBM_ParticleDataOutput_host[g], sizes[pnode]*sizeof(IBM_CUDA_ParticleDataOutput), MPI_BYTE, pnode, REQ_CUDAIBMSENDVEL, comm_cart); g += sizes[pnode]; } } } } COMM_TRACE(fprintf(stderr, "%d: finished send\n", this_node)); free(sizes); } void IBM_cuda_mpi_send_velocities_slave() { Cell *cell; int c, i; MPI_Status status; const int n_part = cells_get_n_particles(); COMM_TRACE(fprintf(stderr, "%d: send_particles_slave, %d particles\n", this_node, n_part)); if (n_part > 0) { int g = 0; IBM_CUDA_ParticleDataOutput *output_sl = new IBM_CUDA_ParticleDataOutput[n_part]; MPI_Recv(output_sl, n_part*sizeof(IBM_CUDA_ParticleDataOutput), MPI_BYTE, 0, REQ_CUDAIBMSENDVEL, comm_cart, &status); for (c = 0; c < local_cells.n; c++) { int npart; cell = local_cells.cell[c]; npart = cell->n; for (i=0;i<npart;i++) { if ( cell->part[i].p.isVirtual ) { cell->part[i].m.v[0] = (double)output_sl[(i+g)].v[0]; cell->part[i].m.v[1] = (double)output_sl[(i+g)].v[1]; cell->part[i].m.v[2] = (double)output_sl[(i+g)].v[2]; } } g += npart; } delete []output_sl; } } #endif
sehrhardt/espresso
src/core/immersed_boundary/ibm_cuda_interface.cpp
C++
gpl-3.0
7,514
# -*- coding: utf-8 -*- ################################################################################## # # Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com) # and 2004-2010 Tiny SPRL (<http://tiny.be>). # # $Id: hr.py 4656 2006-11-24 09:58:42Z Cyp $ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import datetime import math import time from operator import attrgetter from openerp.exceptions import Warning from openerp import tools from openerp.osv import fields, osv from openerp.tools.translate import _ class hr_holidays_status(osv.osv): _name = "hr.holidays.status" _description = "Leave Type" def get_days(self, cr, uid, ids, employee_id, context=None): result = dict((id, dict(max_leaves=0, leaves_taken=0, remaining_leaves=0, virtual_remaining_leaves=0)) for id in ids) holiday_ids = self.pool['hr.holidays'].search(cr, uid, [('employee_id', '=', employee_id), ('state', 'in', ['confirm', 'validate1', 'validate']), ('holiday_status_id', 'in', ids) ], context=context) for holiday in self.pool['hr.holidays'].browse(cr, uid, holiday_ids, context=context): status_dict = result[holiday.holiday_status_id.id] if holiday.type == 'add': status_dict['virtual_remaining_leaves'] += holiday.number_of_days_temp if holiday.state == 'validate': status_dict['max_leaves'] += holiday.number_of_days_temp status_dict['remaining_leaves'] += holiday.number_of_days_temp elif holiday.type == 'remove': # number of days is negative status_dict['virtual_remaining_leaves'] -= holiday.number_of_days_temp if holiday.state == 'validate': status_dict['leaves_taken'] += holiday.number_of_days_temp status_dict['remaining_leaves'] -= holiday.number_of_days_temp return result def _user_left_days(self, cr, uid, ids, name, args, context=None): employee_id = False if context and 'employee_id' in context: employee_id = context['employee_id'] else: employee_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context) if employee_ids: employee_id = employee_ids[0] if employee_id: res = self.get_days(cr, uid, ids, employee_id, context=context) else: res = dict((res_id, {'leaves_taken': 0, 'remaining_leaves': 0, 'max_leaves': 0}) for res_id in ids) return res _columns = { 'name': fields.char('Leave Type', size=64, required=True, translate=True), 'categ_id': fields.many2one('calendar.event.type', 'Meeting Type', help='Once a leave is validated, Odoo will create a corresponding meeting of this type in the calendar.'), 'color_name': fields.selection([('red', 'Red'),('blue','Blue'), ('lightgreen', 'Light Green'), ('lightblue','Light Blue'), ('lightyellow', 'Light Yellow'), ('magenta', 'Magenta'),('lightcyan', 'Light Cyan'),('black', 'Black'),('lightpink', 'Light Pink'),('brown', 'Brown'),('violet', 'Violet'),('lightcoral', 'Light Coral'),('lightsalmon', 'Light Salmon'),('lavender', 'Lavender'),('wheat', 'Wheat'),('ivory', 'Ivory')],'Color in Report', required=True, help='This color will be used in the leaves summary located in Reporting\Leaves by Department.'), 'limit': fields.boolean('Allow to Override Limit', help='If you select this check box, the system allows the employees to take more leaves than the available ones for this type and will not take them into account for the "Remaining Legal Leaves" defined on the employee form.'), 'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the leave type without removing it."), 'max_leaves': fields.function(_user_left_days, string='Maximum Allowed', help='This value is given by the sum of all holidays requests with a positive value.', multi='user_left_days'), 'leaves_taken': fields.function(_user_left_days, string='Leaves Already Taken', help='This value is given by the sum of all holidays requests with a negative value.', multi='user_left_days'), 'remaining_leaves': fields.function(_user_left_days, string='Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken', multi='user_left_days'), 'virtual_remaining_leaves': fields.function(_user_left_days, string='Virtual Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken - Leaves Waiting Approval', multi='user_left_days'), 'double_validation': fields.boolean('Apply Double Validation', help="When selected, the Allocation/Leave Requests for this type require a second validation to be approved."), } _defaults = { 'color_name': 'red', 'active': True, } def name_get(self, cr, uid, ids, context=None): if context is None: context = {} if not context.get('employee_id',False): # leave counts is based on employee_id, would be inaccurate if not based on correct employee return super(hr_holidays_status, self).name_get(cr, uid, ids, context=context) res = [] for record in self.browse(cr, uid, ids, context=context): name = record.name if not record.limit: name = name + (' (%g/%g)' % (record.leaves_taken or 0.0, record.max_leaves or 0.0)) res.append((record.id, name)) return res class hr_holidays(osv.osv): _name = "hr.holidays" _description = "Leave" _order = "type desc, date_from asc" _inherit = ['mail.thread', 'ir.needaction_mixin'] _track = { 'state': { 'hr_holidays.mt_holidays_approved': lambda self, cr, uid, obj, ctx=None: obj.state == 'validate', 'hr_holidays.mt_holidays_refused': lambda self, cr, uid, obj, ctx=None: obj.state == 'refuse', 'hr_holidays.mt_holidays_confirmed': lambda self, cr, uid, obj, ctx=None: obj.state == 'confirm', }, } def _employee_get(self, cr, uid, context=None): emp_id = context.get('default_employee_id', False) if emp_id: return emp_id ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context) if ids: return ids[0] return False def _compute_number_of_days(self, cr, uid, ids, name, args, context=None): result = {} for hol in self.browse(cr, uid, ids, context=context): if hol.type=='remove': result[hol.id] = -hol.number_of_days_temp else: result[hol.id] = hol.number_of_days_temp return result def _get_can_reset(self, cr, uid, ids, name, arg, context=None): """User can reset a leave request if it is its own leave request or if he is an Hr Manager. """ user = self.pool['res.users'].browse(cr, uid, uid, context=context) group_hr_manager_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_hr_manager')[1] if group_hr_manager_id in [g.id for g in user.groups_id]: return dict.fromkeys(ids, True) result = dict.fromkeys(ids, False) for holiday in self.browse(cr, uid, ids, context=context): if holiday.employee_id and holiday.employee_id.user_id and holiday.employee_id.user_id.id == uid: result[holiday.id] = True return result def _check_date(self, cr, uid, ids, context=None): for holiday in self.browse(cr, uid, ids, context=context): domain = [ ('date_from', '<=', holiday.date_to), ('date_to', '>=', holiday.date_from), ('employee_id', '=', holiday.employee_id.id), ('id', '!=', holiday.id), ('state', 'not in', ['cancel', 'refuse']), ] nholidays = self.search_count(cr, uid, domain, context=context) if nholidays: return False return True _check_holidays = lambda self, cr, uid, ids, context=None: self.check_holidays(cr, uid, ids, context=context) _columns = { 'name': fields.char('Description', size=64), 'state': fields.selection([('draft', 'To Submit'), ('cancel', 'Cancelled'),('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved')], 'Status', readonly=True, track_visibility='onchange', copy=False, help='The status is set to \'To Submit\', when a holiday request is created.\ \nThe status is \'To Approve\', when holiday request is confirmed by user.\ \nThe status is \'Refused\', when holiday request is refused by manager.\ \nThe status is \'Approved\', when holiday request is approved by manager.'), 'user_id':fields.related('employee_id', 'user_id', type='many2one', relation='res.users', string='User', store=True), 'date_from': fields.datetime('Start Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, select=True, copy=False), 'date_to': fields.datetime('End Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False), 'holiday_status_id': fields.many2one("hr.holidays.status", "Leave Type", required=True,readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'employee_id': fields.many2one('hr.employee', "Employee", select=True, invisible=False, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'manager_id': fields.many2one('hr.employee', 'First Approval', invisible=False, readonly=True, copy=False, help='This area is automatically filled by the user who validate the leave'), 'notes': fields.text('Reasons',readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'number_of_days_temp': fields.float('Allocation', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False), 'number_of_days': fields.function(_compute_number_of_days, string='Number of Days', store=True), 'meeting_id': fields.many2one('calendar.event', 'Meeting'), 'type': fields.selection([('remove','Leave Request'),('add','Allocation Request')], 'Request Type', required=True, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help="Choose 'Leave Request' if someone wants to take an off-day. \nChoose 'Allocation Request' if you want to increase the number of leaves available for someone", select=True), 'parent_id': fields.many2one('hr.holidays', 'Parent'), 'linked_request_ids': fields.one2many('hr.holidays', 'parent_id', 'Linked Requests',), 'department_id':fields.related('employee_id', 'department_id', string='Department', type='many2one', relation='hr.department', readonly=True, store=True), 'category_id': fields.many2one('hr.employee.category', "Employee Tag", help='Category of Employee', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'holiday_type': fields.selection([('employee','By Employee'),('category','By Employee Tag')], 'Allocation Mode', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help='By Employee: Allocation/Request for individual Employee, By Employee Tag: Allocation/Request for group of employees in category', required=True), 'manager_id2': fields.many2one('hr.employee', 'Second Approval', readonly=True, copy=False, help='This area is automaticly filled by the user who validate the leave with second level (If Leave type need second validation)'), 'double_validation': fields.related('holiday_status_id', 'double_validation', type='boolean', relation='hr.holidays.status', string='Apply Double Validation'), 'can_reset': fields.function( _get_can_reset, type='boolean'), } _defaults = { 'employee_id': _employee_get, 'state': 'confirm', 'type': 'remove', 'user_id': lambda obj, cr, uid, context: uid, 'holiday_type': 'employee' } _constraints = [ (_check_date, 'You can not have 2 leaves that overlaps on same day!', ['date_from','date_to']), (_check_holidays, 'The number of remaining leaves is not sufficient for this leave type', ['state','number_of_days_temp']) ] _sql_constraints = [ ('type_value', "CHECK( (holiday_type='employee' AND employee_id IS NOT NULL) or (holiday_type='category' AND category_id IS NOT NULL))", "The employee or employee category of this request is missing. Please make sure that your user login is linked to an employee."), ('date_check2', "CHECK ( (type='add') OR (date_from <= date_to))", "The start date must be anterior to the end date."), ('date_check', "CHECK ( number_of_days_temp >= 0 )", "The number of days must be greater than 0."), ] def _create_resource_leave(self, cr, uid, leaves, context=None): '''This method will create entry in resource calendar leave object at the time of holidays validated ''' obj_res_leave = self.pool.get('resource.calendar.leaves') for leave in leaves: vals = { 'name': leave.name, 'date_from': leave.date_from, 'holiday_id': leave.id, 'date_to': leave.date_to, 'resource_id': leave.employee_id.resource_id.id, 'calendar_id': leave.employee_id.resource_id.calendar_id.id } obj_res_leave.create(cr, uid, vals, context=context) return True def _remove_resource_leave(self, cr, uid, ids, context=None): '''This method will create entry in resource calendar leave object at the time of holidays cancel/removed''' obj_res_leave = self.pool.get('resource.calendar.leaves') leave_ids = obj_res_leave.search(cr, uid, [('holiday_id', 'in', ids)], context=context) return obj_res_leave.unlink(cr, uid, leave_ids, context=context) def onchange_type(self, cr, uid, ids, holiday_type, employee_id=False, context=None): result = {} if holiday_type == 'employee' and not employee_id: ids_employee = self.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)]) if ids_employee: result['value'] = { 'employee_id': ids_employee[0] } elif holiday_type != 'employee': result['value'] = { 'employee_id': False } return result def onchange_employee(self, cr, uid, ids, employee_id): result = {'value': {'department_id': False}} if employee_id: employee = self.pool.get('hr.employee').browse(cr, uid, employee_id) result['value'] = {'department_id': employee.department_id.id} return result # TODO: can be improved using resource calendar method def _get_number_of_days(self, date_from, date_to): """Returns a float equals to the timedelta between two dates given as string.""" DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" from_dt = datetime.datetime.strptime(date_from, DATETIME_FORMAT) to_dt = datetime.datetime.strptime(date_to, DATETIME_FORMAT) timedelta = to_dt - from_dt diff_day = timedelta.days + float(timedelta.seconds) / 86400 return diff_day def unlink(self, cr, uid, ids, context=None): for rec in self.browse(cr, uid, ids, context=context): if rec.state not in ['draft', 'cancel', 'confirm']: raise osv.except_osv(_('Warning!'),_('You cannot delete a leave which is in %s state.')%(rec.state)) return super(hr_holidays, self).unlink(cr, uid, ids, context) def onchange_date_from(self, cr, uid, ids, date_to, date_from): """ If there are no date set for date_to, automatically set one 8 hours later than the date_from. Also update the number_of_days. """ # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.')) result = {'value': {}} # No date_to set so far: automatically compute one 8 hours later if date_from and not date_to: date_to_with_delta = datetime.datetime.strptime(date_from, tools.DEFAULT_SERVER_DATETIME_FORMAT) + datetime.timedelta(hours=8) result['value']['date_to'] = str(date_to_with_delta) # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1 else: result['value']['number_of_days_temp'] = 0 return result def onchange_date_to(self, cr, uid, ids, date_to, date_from): """ Update the number_of_days. """ # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.')) result = {'value': {}} # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1 else: result['value']['number_of_days_temp'] = 0 return result def add_follower(self, cr, uid, ids, employee_id, context=None): employee = self.pool['hr.employee'].browse(cr, uid, employee_id, context=context) if employee.user_id: self.message_subscribe(cr, uid, ids, [employee.user_id.partner_id.id], context=context) def create(self, cr, uid, values, context=None): """ Override to avoid automatic logging of creation """ if context is None: context = {} employee_id = values.get('employee_id', False) context = dict(context, mail_create_nolog=True, mail_create_nosubscribe=True) if values.get('state') and values['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'): raise osv.except_osv(_('Warning!'), _('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state')) hr_holiday_id = super(hr_holidays, self).create(cr, uid, values, context=context) self.add_follower(cr, uid, [hr_holiday_id], employee_id, context=context) return hr_holiday_id def write(self, cr, uid, ids, vals, context=None): employee_id = vals.get('employee_id', False) if vals.get('state') and vals['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'): raise osv.except_osv(_('Warning!'), _('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % vals.get('state')) hr_holiday_id = super(hr_holidays, self).write(cr, uid, ids, vals, context=context) self.add_follower(cr, uid, ids, employee_id, context=context) return hr_holiday_id def holidays_reset(self, cr, uid, ids, context=None): self.write(cr, uid, ids, { 'state': 'draft', 'manager_id': False, 'manager_id2': False, }) to_unlink = [] for record in self.browse(cr, uid, ids, context=context): for record2 in record.linked_request_ids: self.holidays_reset(cr, uid, [record2.id], context=context) to_unlink.append(record2.id) if to_unlink: self.unlink(cr, uid, to_unlink, context=context) return True def holidays_first_validate(self, cr, uid, ids, context=None): obj_emp = self.pool.get('hr.employee') ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)]) manager = ids2 and ids2[0] or False self.holidays_first_validate_notificate(cr, uid, ids, context=context) return self.write(cr, uid, ids, {'state':'validate1', 'manager_id': manager}) def holidays_validate(self, cr, uid, ids, context=None): obj_emp = self.pool.get('hr.employee') ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)]) manager = ids2 and ids2[0] or False self.write(cr, uid, ids, {'state':'validate'}) data_holiday = self.browse(cr, uid, ids) for record in data_holiday: if record.double_validation: self.write(cr, uid, [record.id], {'manager_id2': manager}) else: self.write(cr, uid, [record.id], {'manager_id': manager}) if record.holiday_type == 'employee' and record.type == 'remove': meeting_obj = self.pool.get('calendar.event') meeting_vals = { 'name': record.name or _('Leave Request'), 'categ_ids': record.holiday_status_id.categ_id and [(6,0,[record.holiday_status_id.categ_id.id])] or [], 'duration': record.number_of_days_temp * 8, 'description': record.notes, 'user_id': record.user_id.id, 'start': record.date_from, 'stop': record.date_to, 'allday': False, 'state': 'open', # to block that meeting date in the calendar 'class': 'confidential' } #Add the partner_id (if exist) as an attendee if record.user_id and record.user_id.partner_id: meeting_vals['partner_ids'] = [(4,record.user_id.partner_id.id)] ctx_no_email = dict(context or {}, no_email=True) meeting_id = meeting_obj.create(cr, uid, meeting_vals, context=ctx_no_email) self._create_resource_leave(cr, uid, [record], context=context) self.write(cr, uid, ids, {'meeting_id': meeting_id}) elif record.holiday_type == 'category': emp_ids = obj_emp.search(cr, uid, [('category_ids', 'child_of', [record.category_id.id])]) leave_ids = [] batch_context = dict(context, mail_notify_force_send=False) for emp in obj_emp.browse(cr, uid, emp_ids, context=context): vals = { 'name': record.name, 'type': record.type, 'holiday_type': 'employee', 'holiday_status_id': record.holiday_status_id.id, 'date_from': record.date_from, 'date_to': record.date_to, 'notes': record.notes, 'number_of_days_temp': record.number_of_days_temp, 'parent_id': record.id, 'employee_id': emp.id } leave_ids.append(self.create(cr, uid, vals, context=batch_context)) for leave_id in leave_ids: # TODO is it necessary to interleave the calls? for sig in ('confirm', 'validate', 'second_validate'): self.signal_workflow(cr, uid, [leave_id], sig) return True def holidays_confirm(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context=context): if record.employee_id and record.employee_id.parent_id and record.employee_id.parent_id.user_id: self.message_subscribe_users(cr, uid, [record.id], user_ids=[record.employee_id.parent_id.user_id.id], context=context) return self.write(cr, uid, ids, {'state': 'confirm'}) def holidays_refuse(self, cr, uid, ids, context=None): obj_emp = self.pool.get('hr.employee') ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)]) manager = ids2 and ids2[0] or False for holiday in self.browse(cr, uid, ids, context=context): if holiday.state == 'validate1': self.write(cr, uid, [holiday.id], {'state': 'refuse', 'manager_id': manager}) else: self.write(cr, uid, [holiday.id], {'state': 'refuse', 'manager_id2': manager}) self.holidays_cancel(cr, uid, ids, context=context) return True def holidays_cancel(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context=context): # Delete the meeting if record.meeting_id: record.meeting_id.unlink() # If a category that created several holidays, cancel all related self.signal_workflow(cr, uid, map(attrgetter('id'), record.linked_request_ids or []), 'refuse') self._remove_resource_leave(cr, uid, ids, context=context) return True def check_holidays(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context=context): if record.holiday_type != 'employee' or record.type != 'remove' or not record.employee_id or record.holiday_status_id.limit: continue leave_days = self.pool.get('hr.holidays.status').get_days(cr, uid, [record.holiday_status_id.id], record.employee_id.id, context=context)[record.holiday_status_id.id] if leave_days['remaining_leaves'] < 0 or leave_days['virtual_remaining_leaves'] < 0: # Raising a warning gives a more user-friendly feedback than the default constraint error raise Warning(_('The number of remaining leaves is not sufficient for this leave type.\n' 'Please verify also the leaves waiting for validation.')) return True # ----------------------------- # OpenChatter and notifications # ----------------------------- def _needaction_domain_get(self, cr, uid, context=None): emp_obj = self.pool.get('hr.employee') empids = emp_obj.search(cr, uid, [('parent_id.user_id', '=', uid)], context=context) dom = ['&', ('state', '=', 'confirm'), ('employee_id', 'in', empids)] # if this user is a hr.manager, he should do second validations if self.pool.get('res.users').has_group(cr, uid, 'base.group_hr_manager'): dom = ['|'] + dom + [('state', '=', 'validate1')] return dom def holidays_first_validate_notificate(self, cr, uid, ids, context=None): for obj in self.browse(cr, uid, ids, context=context): self.message_post(cr, uid, [obj.id], _("Request approved, waiting second validation."), context=context) class resource_calendar_leaves(osv.osv): _inherit = "resource.calendar.leaves" _description = "Leave Detail" _columns = { 'holiday_id': fields.many2one("hr.holidays", "Leave Request"), } class hr_employee(osv.osv): _inherit="hr.employee" def create(self, cr, uid, vals, context=None): # don't pass the value of remaining leave if it's 0 at the creation time, otherwise it will trigger the inverse # function _set_remaining_days and the system may not be configured for. Note that we don't have this problem on # the write because the clients only send the fields that have been modified. if 'remaining_leaves' in vals and not vals['remaining_leaves']: del(vals['remaining_leaves']) return super(hr_employee, self).create(cr, uid, vals, context=context) def _set_remaining_days(self, cr, uid, empl_id, name, value, arg, context=None): employee = self.browse(cr, uid, empl_id, context=context) diff = value - employee.remaining_leaves type_obj = self.pool.get('hr.holidays.status') holiday_obj = self.pool.get('hr.holidays') # Find for holidays status status_ids = type_obj.search(cr, uid, [('limit', '=', False)], context=context) if len(status_ids) != 1 : raise osv.except_osv(_('Warning!'),_("The feature behind the field 'Remaining Legal Leaves' can only be used when there is only one leave type with the option 'Allow to Override Limit' unchecked. (%s Found). Otherwise, the update is ambiguous as we cannot decide on which leave type the update has to be done. \nYou may prefer to use the classic menus 'Leave Requests' and 'Allocation Requests' located in 'Human Resources \ Leaves' to manage the leave days of the employees if the configuration does not allow to use this field.") % (len(status_ids))) status_id = status_ids and status_ids[0] or False if not status_id: return False if diff > 0: leave_id = holiday_obj.create(cr, uid, {'name': _('Allocation for %s') % employee.name, 'employee_id': employee.id, 'holiday_status_id': status_id, 'type': 'add', 'holiday_type': 'employee', 'number_of_days_temp': diff}, context=context) elif diff < 0: raise osv.except_osv(_('Warning!'), _('You cannot reduce validated allocation requests')) else: return False for sig in ('confirm', 'validate', 'second_validate'): holiday_obj.signal_workflow(cr, uid, [leave_id], sig) return True def _get_remaining_days(self, cr, uid, ids, name, args, context=None): cr.execute("""SELECT sum(h.number_of_days) as days, h.employee_id from hr_holidays h join hr_holidays_status s on (s.id=h.holiday_status_id) where h.state='validate' and s.limit=False and h.employee_id in %s group by h.employee_id""", (tuple(ids),)) res = cr.dictfetchall() remaining = {} for r in res: remaining[r['employee_id']] = r['days'] for employee_id in ids: if not remaining.get(employee_id): remaining[employee_id] = 0.0 return remaining def _get_leave_status(self, cr, uid, ids, name, args, context=None): holidays_obj = self.pool.get('hr.holidays') holidays_id = holidays_obj.search(cr, uid, [('employee_id', 'in', ids), ('date_from','<=',time.strftime('%Y-%m-%d %H:%M:%S')), ('date_to','>=',time.strftime('%Y-%m-%d 23:59:59')),('type','=','remove'),('state','not in',('cancel','refuse'))], context=context) result = {} for id in ids: result[id] = { 'current_leave_state': False, 'current_leave_id': False, 'leave_date_from':False, 'leave_date_to':False, } for holiday in self.pool.get('hr.holidays').browse(cr, uid, holidays_id, context=context): result[holiday.employee_id.id]['leave_date_from'] = holiday.date_from result[holiday.employee_id.id]['leave_date_to'] = holiday.date_to result[holiday.employee_id.id]['current_leave_state'] = holiday.state result[holiday.employee_id.id]['current_leave_id'] = holiday.holiday_status_id.id return result def _leaves_count(self, cr, uid, ids, field_name, arg, context=None): Holidays = self.pool['hr.holidays'] return { employee_id: Holidays.search_count(cr,uid, [('employee_id', '=', employee_id), ('type', '=', 'remove')], context=context) for employee_id in ids } _columns = { 'remaining_leaves': fields.function(_get_remaining_days, string='Remaining Legal Leaves', fnct_inv=_set_remaining_days, type="float", help='Total number of legal leaves allocated to this employee, change this value to create allocation/leave request. Total based on all the leave types without overriding limit.'), 'current_leave_state': fields.function(_get_leave_status, multi="leave_status", string="Current Leave Status", type="selection", selection=[('draft', 'New'), ('confirm', 'Waiting Approval'), ('refuse', 'Refused'), ('validate1', 'Waiting Second Approval'), ('validate', 'Approved'), ('cancel', 'Cancelled')]), 'current_leave_id': fields.function(_get_leave_status, multi="leave_status", string="Current Leave Type",type='many2one', relation='hr.holidays.status'), 'leave_date_from': fields.function(_get_leave_status, multi='leave_status', type='date', string='From Date'), 'leave_date_to': fields.function(_get_leave_status, multi='leave_status', type='date', string='To Date'), 'leaves_count': fields.function(_leaves_count, type='integer', string='Leaves'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ncliam/serverpos
openerp/addons/hr_holidays/hr_holidays.py
Python
agpl-3.0
34,256
<?php /** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ /** * Generic filter * @api */ class default_filter { public $_component; public function __construct() { } /** * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead */ public function default_filter() { $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code'; if (isset($GLOBALS['log'])) { $GLOBALS['log']->deprecated($deprecatedMessage); } else { trigger_error($deprecatedMessage, E_USER_DEPRECATED); } self::__construct(); } public function setComponent($component) { $this->_component = $component; } /** * getList * Returns a nested array containing a key/value pair(s) of a source record * * @param array $args Array of arguments to search/filter by * @param string $module String optional value of the module that the connector framework is attempting to map to * @return array of key/value pair(s) of source record; empty Array if no results are found */ public function getList($args, $module) { $args = $this->_component->mapInput($args, $module); return $this->_component->getSource()->getList($args, $module); } }
ChangezKhan/SuiteCRM
include/connectors/filters/default/filter.php
PHP
agpl-3.0
3,456
// --------------------------------------------------------------------- // // Copyright (C) 1998 - 2014 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // check accuracy of various quadrature formulas by using them to // integrate polynomials of increasing degree, and finding the degree // until which they integrate exactly #include "../tests.h" #include <iomanip> #include <fstream> #include <deal.II/base/logstream.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/base/qprojector.h> #include <cmath> template <int dim> void fill_vector (std::vector<Quadrature<dim> *> &quadratures) { quadratures.push_back (new QMidpoint<dim>()); quadratures.push_back (new QTrapez<dim>()); quadratures.push_back (new QSimpson<dim>()); quadratures.push_back (new QMilne<dim>()); quadratures.push_back (new QWeddle<dim>()); for (unsigned int i=0; i<9; ++i) { quadratures.push_back (new QGauss<dim>(i)); } QMilne<1> q1d; quadratures.push_back (new Quadrature<dim>(q1d)); for (unsigned int i=2; i<8; ++i) { quadratures.push_back (new QGaussLobatto<dim>(i)); } } template <int dim> void check_cells (std::vector<Quadrature<dim>*> &quadratures) { Quadrature<dim> quadrature; for (unsigned int n=0; n<quadratures.size(); ++n) { quadrature = *quadratures[n]; const std::vector<Point<dim> > &points=quadrature.get_points(); const std::vector<double> &weights=quadrature.get_weights(); deallog << "Quadrature no." << n; unsigned int i=0; double quadrature_int=0; double exact_int=0; double err = 0; do { ++i; quadrature_int=0; // Check the polynomial x^i*y^i for (unsigned int x=0; x<quadrature.size(); ++x) { double f=1.; switch (dim) { case 3: f *= std::pow(static_cast<double>(points[x](2)), i*1.0); case 2: f *= std::pow(static_cast<double>(points[x](1)), i*1.0); case 1: f *= std::pow(static_cast<double>(points[x](0)), i*1.0); } quadrature_int+=f*weights[x]; } // the exact integral is 1/(i+1) exact_int=1./std::pow(static_cast<double>(i+1),dim); err = std::fabs(quadrature_int-exact_int); } while (err<1e-14); // Uncomment here for testing // deallog << " (Int " << quadrature_int << ',' << exact_int << ")"; deallog << " is exact for polynomials of degree " << i-1 << std::endl; if (dim==1) { // check the ordering of // the quadrature points bool in_order=true; for (unsigned int x=1; x<quadrature.size(); ++x) { if (points[x](0)<=points[x-1](0)) in_order=false; } if (!in_order) for (unsigned int x=0; x<quadrature.size(); ++x) deallog << points[x] << std::endl; } } } template <int dim> void check_faces (const std::vector<Quadrature<dim-1>*>& quadratures, const bool sub) { if (sub) deallog.push("subfaces"); else deallog.push("faces"); for (unsigned int n=0; n<quadratures.size(); ++n) { Quadrature<dim> quadrature (sub == false? QProjector<dim>::project_to_all_faces(*quadratures[n]) : QProjector<dim>::project_to_all_subfaces(*quadratures[n])); const std::vector<Point<dim> > &points=quadrature.get_points(); const std::vector<double> &weights=quadrature.get_weights(); deallog << "Quadrature no." << n; unsigned int i=0; long double quadrature_int=0; double exact_int=0; double err = 0; do { ++i; quadrature_int=0; // Check the polynomial // x^i*y^i*z^i for (unsigned int x=0; x<quadrature.size(); ++x) { long double f=1.; switch (dim) { case 3: f *= std::pow((long double) points[x](2), i*1.0L); case 2: f *= std::pow((long double) points[x](1), i*1.0L); case 1: f *= std::pow((long double) points[x](0), i*1.0L); } quadrature_int+=f*weights[x]; } // the exact integral is // 1/(i+1)^(dim-1) switch (dim) { case 2: exact_int = 2 * (sub ? 2:1) / (double) (i+1); break; case 3: exact_int = 3 * (sub ? (4+2+2):1)*8 / (double) (i+1)/(i+1); break; } err = std::fabs(quadrature_int-exact_int); } // for comparison: use factor 8 in case // of dim==3, as we integrate 8 times // over the whole surface (all // combinations of face_orientation, // face_flip and face_rotation) while (err < (dim==3 ? 8 : 1) * 2e-14); // Uncomment here for testing // deallog << " (Int " << quadrature_int << '-' << exact_int << '=' << err << ")"; deallog << " is exact for polynomials of degree " << i-1 << std::endl; } deallog.pop(); } int main() { std::ofstream logfile("output"); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); std::vector<Quadrature<1> *> q1; std::vector<Quadrature<2> *> q2; std::vector<Quadrature<3> *> q3; fill_vector (q1); fill_vector (q2); fill_vector (q3); deallog.push("1d"); check_cells(q1); deallog.pop(); deallog.push("2d"); check_cells(q2); check_faces<2>(q1,false); check_faces<2>(q1,true); deallog.pop(); deallog.push("3d"); check_cells(q3); check_faces<3>(q2,false); check_faces<3>(q2,true); deallog.pop(); // delete objects again to avoid // messages about memory leaks when // using purify or other memory // checkers for (unsigned int i=0; i<q1.size(); ++i) delete q1[i]; for (unsigned int i=0; i<q2.size(); ++i) delete q2[i]; for (unsigned int i=0; i<q3.size(); ++i) delete q3[i]; }
johntfoster/dealii
tests/base/quadrature_test.cc
C++
lgpl-2.1
6,728
// --------------------------------------------------------------------- // // Copyright (C) 2003 - 2014 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test that the grid generated by GridGenerator::cylinder_shell<3> works as // expected #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/grid_generator.h> #include <fstream> #include <iomanip> int main () { std::ofstream logfile("output"); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); deallog << std::setprecision (2); // generate a hyperball in 3d Triangulation<3> tria; GridGenerator::cylinder_shell (tria, 1, .8, 1); // make sure that all cells have positive // volume for (Triangulation<3>::active_cell_iterator cell=tria.begin_active(); cell!=tria.end(); ++cell) deallog << cell << ' ' << cell->measure () << std::endl; }
natashasharma/dealii
tests/bits/cylinder_shell_01.cc
C++
lgpl-2.1
1,499
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.index; import org.apache.lucene.document.NumericDocValuesField; import org.elasticsearch.Version; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.IndexingSlowLog.SlowLogParsedDocumentPrinter; import org.elasticsearch.index.mapper.ParsedDocument; import org.elasticsearch.index.mapper.SeqNoFieldMapper; import org.elasticsearch.test.ESTestCase; import java.io.IOException; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; public class IndexingSlowLogTests extends ESTestCase { public void testSlowLogParsedDocumentPrinterSourceToLog() throws IOException { BytesReference source = JsonXContent.contentBuilder().startObject().field("foo", "bar").endObject().bytes(); ParsedDocument pd = new ParsedDocument(new NumericDocValuesField("version", 1), SeqNoFieldMapper.SequenceIDFields.emptySeqID(), "id", "test", null, null, source, XContentType.JSON, null); Index index = new Index("foo", "123"); // Turning off document logging doesn't log source[] SlowLogParsedDocumentPrinter p = new SlowLogParsedDocumentPrinter(index, pd, 10, true, 0); assertThat(p.toString(), not(containsString("source["))); // Turning on document logging logs the whole thing p = new SlowLogParsedDocumentPrinter(index, pd, 10, true, Integer.MAX_VALUE); assertThat(p.toString(), containsString("source[{\"foo\":\"bar\"}]")); // And you can truncate the source p = new SlowLogParsedDocumentPrinter(index, pd, 10, true, 3); assertThat(p.toString(), containsString("source[{\"f]")); // And you can truncate the source p = new SlowLogParsedDocumentPrinter(index, pd, 10, true, 3); assertThat(p.toString(), containsString("source[{\"f]")); assertThat(p.toString(), startsWith("[foo/123] took")); } public void testReformatSetting() { IndexMetaData metaData = newIndexMeta("index", Settings.builder() .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING.getKey(), false) .build()); IndexSettings settings = new IndexSettings(metaData, Settings.EMPTY); IndexingSlowLog log = new IndexingSlowLog(settings); assertFalse(log.isReformat()); settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING.getKey(), "true").build())); assertTrue(log.isReformat()); settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING.getKey(), "false").build())); assertFalse(log.isReformat()); settings.updateIndexMetaData(newIndexMeta("index", Settings.EMPTY)); assertTrue(log.isReformat()); metaData = newIndexMeta("index", Settings.builder() .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .build()); settings = new IndexSettings(metaData, Settings.EMPTY); log = new IndexingSlowLog(settings); assertTrue(log.isReformat()); try { settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING.getKey(), "NOT A BOOLEAN").build())); fail(); } catch (IllegalArgumentException ex) { final String expected = "illegal value can't update [index.indexing.slowlog.reformat] from [true] to [NOT A BOOLEAN]"; assertThat(ex, hasToString(containsString(expected))); assertNotNull(ex.getCause()); assertThat(ex.getCause(), instanceOf(IllegalArgumentException.class)); final IllegalArgumentException cause = (IllegalArgumentException) ex.getCause(); assertThat(cause, hasToString(containsString("Failed to parse value [NOT A BOOLEAN] as only [true] or [false] are allowed."))); } assertTrue(log.isReformat()); } public void testLevelSetting() { SlowLogLevel level = randomFrom(SlowLogLevel.values()); IndexMetaData metaData = newIndexMeta("index", Settings.builder() .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING.getKey(), level) .build()); IndexSettings settings = new IndexSettings(metaData, Settings.EMPTY); IndexingSlowLog log = new IndexingSlowLog(settings); assertEquals(level, log.getLevel()); level = randomFrom(SlowLogLevel.values()); settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING.getKey(), level).build())); assertEquals(level, log.getLevel()); level = randomFrom(SlowLogLevel.values()); settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING.getKey(), level).build())); assertEquals(level, log.getLevel()); settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING.getKey(), level).build())); assertEquals(level, log.getLevel()); settings.updateIndexMetaData(newIndexMeta("index", Settings.EMPTY)); assertEquals(SlowLogLevel.TRACE, log.getLevel()); metaData = newIndexMeta("index", Settings.builder() .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .build()); settings = new IndexSettings(metaData, Settings.EMPTY); log = new IndexingSlowLog(settings); assertTrue(log.isReformat()); try { settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING.getKey(), "NOT A LEVEL").build())); fail(); } catch (IllegalArgumentException ex) { final String expected = "illegal value can't update [index.indexing.slowlog.level] from [TRACE] to [NOT A LEVEL]"; assertThat(ex, hasToString(containsString(expected))); assertNotNull(ex.getCause()); assertThat(ex.getCause(), instanceOf(IllegalArgumentException.class)); final IllegalArgumentException cause = (IllegalArgumentException) ex.getCause(); assertThat(cause, hasToString(containsString("No enum constant org.elasticsearch.index.SlowLogLevel.NOT A LEVEL"))); } assertEquals(SlowLogLevel.TRACE, log.getLevel()); } public void testSetLevels() { IndexMetaData metaData = newIndexMeta("index", Settings.builder() .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE_SETTING.getKey(), "100ms") .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG_SETTING.getKey(), "200ms") .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO_SETTING.getKey(), "300ms") .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN_SETTING.getKey(), "400ms") .build()); IndexSettings settings = new IndexSettings(metaData, Settings.EMPTY); IndexingSlowLog log = new IndexingSlowLog(settings); assertEquals(TimeValue.timeValueMillis(100).nanos(), log.getIndexTraceThreshold()); assertEquals(TimeValue.timeValueMillis(200).nanos(), log.getIndexDebugThreshold()); assertEquals(TimeValue.timeValueMillis(300).nanos(), log.getIndexInfoThreshold()); assertEquals(TimeValue.timeValueMillis(400).nanos(), log.getIndexWarnThreshold()); settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE_SETTING.getKey(), "120ms") .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG_SETTING.getKey(), "220ms") .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO_SETTING.getKey(), "320ms") .put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN_SETTING.getKey(), "420ms").build())); assertEquals(TimeValue.timeValueMillis(120).nanos(), log.getIndexTraceThreshold()); assertEquals(TimeValue.timeValueMillis(220).nanos(), log.getIndexDebugThreshold()); assertEquals(TimeValue.timeValueMillis(320).nanos(), log.getIndexInfoThreshold()); assertEquals(TimeValue.timeValueMillis(420).nanos(), log.getIndexWarnThreshold()); metaData = newIndexMeta("index", Settings.builder() .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .build()); settings.updateIndexMetaData(metaData); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexTraceThreshold()); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexDebugThreshold()); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexInfoThreshold()); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexWarnThreshold()); settings = new IndexSettings(metaData, Settings.EMPTY); log = new IndexingSlowLog(settings); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexTraceThreshold()); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexDebugThreshold()); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexInfoThreshold()); assertEquals(TimeValue.timeValueMillis(-1).nanos(), log.getIndexWarnThreshold()); try { settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE_SETTING.getKey(), "NOT A TIME VALUE").build())); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.indexing.slowlog.threshold.index.trace"); } try { settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG_SETTING.getKey(), "NOT A TIME VALUE").build())); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.indexing.slowlog.threshold.index.debug"); } try { settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO_SETTING.getKey(), "NOT A TIME VALUE").build())); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.indexing.slowlog.threshold.index.info"); } try { settings.updateIndexMetaData(newIndexMeta("index", Settings.builder().put(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN_SETTING.getKey(), "NOT A TIME VALUE").build())); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.indexing.slowlog.threshold.index.warn"); } } private void assertTimeValueException(final IllegalArgumentException e, final String key) { final String expected = "illegal value can't update [" + key + "] from [-1] to [NOT A TIME VALUE]"; assertThat(e, hasToString(containsString(expected))); assertNotNull(e.getCause()); assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); final IllegalArgumentException cause = (IllegalArgumentException) e.getCause(); final String causeExpected = "failed to parse setting [" + key + "] with value [NOT A TIME VALUE] as a time value: unit is missing or unrecognized"; assertThat(cause, hasToString(containsString(causeExpected))); } private IndexMetaData newIndexMeta(String name, Settings indexSettings) { Settings build = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(indexSettings) .build(); IndexMetaData metaData = IndexMetaData.builder(name).settings(build).build(); return metaData; } }
jimczi/elasticsearch
core/src/test/java/org/elasticsearch/index/IndexingSlowLogTests.java
Java
apache-2.0
13,647
/* Copyright 2014 The Kubernetes 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 apiserver import ( "io/ioutil" "net/http" "net/http/httptest" "reflect" "regexp" "strings" "sync" "testing" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/util/sets" ) type fakeRL bool func (fakeRL) Stop() {} func (f fakeRL) CanAccept() bool { return bool(f) } func (f fakeRL) Accept() {} func expectHTTP(url string, code int, t *testing.T) { r, err := http.Get(url) if err != nil { t.Errorf("unexpected error: %v", err) return } if r.StatusCode != code { t.Errorf("unexpected response: %v", r.StatusCode) } } func getPath(resource, namespace, name string) string { return testapi.Default.ResourcePath(resource, namespace, name) } func pathWithPrefix(prefix, resource, namespace, name string) string { return testapi.Default.ResourcePathWithPrefix(prefix, resource, namespace, name) } func TestMaxInFlight(t *testing.T) { const Iterations = 3 block := sync.WaitGroup{} block.Add(1) sem := make(chan bool, Iterations) re := regexp.MustCompile("[.*\\/watch][^\\/proxy.*]") // Calls verifies that the server is actually blocked up before running the rest of the test calls := &sync.WaitGroup{} calls.Add(Iterations * 3) server := httptest.NewServer(MaxInFlightLimit(sem, re, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.Contains(r.URL.Path, "dontwait") { return } if calls != nil { calls.Done() } block.Wait() }))) defer server.Close() // These should hang, but not affect accounting. for i := 0; i < Iterations; i++ { // These should hang waiting on block... go func() { expectHTTP(server.URL+"/foo/bar/watch", http.StatusOK, t) }() } for i := 0; i < Iterations; i++ { // These should hang waiting on block... go func() { expectHTTP(server.URL+"/proxy/foo/bar", http.StatusOK, t) }() } expectHTTP(server.URL+"/dontwait", http.StatusOK, t) for i := 0; i < Iterations; i++ { // These should hang waiting on block... go func() { expectHTTP(server.URL, http.StatusOK, t) }() } calls.Wait() calls = nil // Do this multiple times to show that it rate limit rejected requests don't block. for i := 0; i < 2; i++ { expectHTTP(server.URL, errors.StatusTooManyRequests, t) } // Validate that non-accounted URLs still work expectHTTP(server.URL+"/dontwait/watch", http.StatusOK, t) block.Done() // Show that we recover from being blocked up. expectHTTP(server.URL, http.StatusOK, t) } func TestReadOnly(t *testing.T) { server := httptest.NewServer(ReadOnly(http.HandlerFunc( func(w http.ResponseWriter, req *http.Request) { if req.Method != "GET" { t.Errorf("Unexpected call: %v", req.Method) } }, ))) defer server.Close() for _, verb := range []string{"GET", "POST", "PUT", "DELETE", "CREATE"} { req, err := http.NewRequest(verb, server.URL, nil) if err != nil { t.Fatalf("Couldn't make request: %v", err) } http.DefaultClient.Do(req) } } func TestTimeout(t *testing.T) { sendResponse := make(chan struct{}, 1) writeErrors := make(chan error, 1) timeout := make(chan time.Time, 1) resp := "test response" timeoutResp := "test timeout" ts := httptest.NewServer(TimeoutHandler(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { <-sendResponse _, err := w.Write([]byte(resp)) writeErrors <- err }), func(*http.Request) (<-chan time.Time, string) { return timeout, timeoutResp })) defer ts.Close() // No timeouts sendResponse <- struct{}{} res, err := http.Get(ts.URL) if err != nil { t.Error(err) } if res.StatusCode != http.StatusOK { t.Errorf("got res.StatusCode %d; expected %d", res.StatusCode, http.StatusOK) } body, _ := ioutil.ReadAll(res.Body) if string(body) != resp { t.Errorf("got body %q; expected %q", string(body), resp) } if err := <-writeErrors; err != nil { t.Errorf("got unexpected Write error on first request: %v", err) } // Times out timeout <- time.Time{} res, err = http.Get(ts.URL) if err != nil { t.Error(err) } if res.StatusCode != http.StatusGatewayTimeout { t.Errorf("got res.StatusCode %d; expected %d", res.StatusCode, http.StatusServiceUnavailable) } body, _ = ioutil.ReadAll(res.Body) if string(body) != timeoutResp { t.Errorf("got body %q; expected %q", string(body), timeoutResp) } // Now try to send a response sendResponse <- struct{}{} if err := <-writeErrors; err != http.ErrHandlerTimeout { t.Errorf("got Write error of %v; expected %v", err, http.ErrHandlerTimeout) } } func TestGetAPIRequestInfo(t *testing.T) { successCases := []struct { method string url string expectedVerb string expectedAPIVersion string expectedNamespace string expectedResource string expectedSubresource string expectedKind string expectedName string expectedParts []string }{ // resource paths {"GET", "/namespaces", "list", "", "", "namespaces", "", "Namespace", "", []string{"namespaces"}}, {"GET", "/namespaces/other", "get", "", "other", "namespaces", "", "Namespace", "other", []string{"namespaces", "other"}}, {"GET", "/namespaces/other/pods", "list", "", "other", "pods", "", "Pod", "", []string{"pods"}}, {"GET", "/namespaces/other/pods/foo", "get", "", "other", "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"GET", "/pods", "list", "", api.NamespaceAll, "pods", "", "Pod", "", []string{"pods"}}, {"GET", "/namespaces/other/pods/foo", "get", "", "other", "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"GET", "/namespaces/other/pods", "list", "", "other", "pods", "", "Pod", "", []string{"pods"}}, // special verbs {"GET", "/proxy/namespaces/other/pods/foo", "proxy", "", "other", "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"GET", "/redirect/namespaces/other/pods/foo", "redirect", "", "other", "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"GET", "/watch/pods", "watch", "", api.NamespaceAll, "pods", "", "Pod", "", []string{"pods"}}, {"GET", "/watch/namespaces/other/pods", "watch", "", "other", "pods", "", "Pod", "", []string{"pods"}}, // fully-qualified paths {"GET", getPath("pods", "other", ""), "list", testapi.Default.Version(), "other", "pods", "", "Pod", "", []string{"pods"}}, {"GET", getPath("pods", "other", "foo"), "get", testapi.Default.Version(), "other", "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"GET", getPath("pods", "", ""), "list", testapi.Default.Version(), api.NamespaceAll, "pods", "", "Pod", "", []string{"pods"}}, {"POST", getPath("pods", "", ""), "create", testapi.Default.Version(), api.NamespaceAll, "pods", "", "Pod", "", []string{"pods"}}, {"GET", getPath("pods", "", "foo"), "get", testapi.Default.Version(), api.NamespaceAll, "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"GET", pathWithPrefix("proxy", "pods", "", "foo"), "proxy", testapi.Default.Version(), api.NamespaceAll, "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"GET", pathWithPrefix("watch", "pods", "", ""), "watch", testapi.Default.Version(), api.NamespaceAll, "pods", "", "Pod", "", []string{"pods"}}, {"GET", pathWithPrefix("redirect", "pods", "", ""), "redirect", testapi.Default.Version(), api.NamespaceAll, "pods", "", "Pod", "", []string{"pods"}}, {"GET", pathWithPrefix("watch", "pods", "other", ""), "watch", testapi.Default.Version(), "other", "pods", "", "Pod", "", []string{"pods"}}, // subresource identification {"GET", "/namespaces/other/pods/foo/status", "get", "", "other", "pods", "status", "Pod", "foo", []string{"pods", "foo", "status"}}, {"PUT", "/namespaces/other/finalize", "update", "", "other", "finalize", "", "", "", []string{"finalize"}}, // verb identification {"PATCH", "/namespaces/other/pods/foo", "patch", "", "other", "pods", "", "Pod", "foo", []string{"pods", "foo"}}, {"DELETE", "/namespaces/other/pods/foo", "delete", "", "other", "pods", "", "Pod", "foo", []string{"pods", "foo"}}, } apiRequestInfoResolver := &APIRequestInfoResolver{sets.NewString("api"), testapi.Default.RESTMapper()} for _, successCase := range successCases { req, _ := http.NewRequest(successCase.method, successCase.url, nil) apiRequestInfo, err := apiRequestInfoResolver.GetAPIRequestInfo(req) if err != nil { t.Errorf("Unexpected error for url: %s %v", successCase.url, err) } if successCase.expectedVerb != apiRequestInfo.Verb { t.Errorf("Unexpected verb for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedVerb, apiRequestInfo.Verb) } if successCase.expectedAPIVersion != apiRequestInfo.APIVersion { t.Errorf("Unexpected apiVersion for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedAPIVersion, apiRequestInfo.APIVersion) } if successCase.expectedNamespace != apiRequestInfo.Namespace { t.Errorf("Unexpected namespace for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedNamespace, apiRequestInfo.Namespace) } if successCase.expectedKind != apiRequestInfo.Kind { t.Errorf("Unexpected kind for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedKind, apiRequestInfo.Kind) } if successCase.expectedResource != apiRequestInfo.Resource { t.Errorf("Unexpected resource for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedResource, apiRequestInfo.Resource) } if successCase.expectedSubresource != apiRequestInfo.Subresource { t.Errorf("Unexpected resource for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedSubresource, apiRequestInfo.Subresource) } if successCase.expectedName != apiRequestInfo.Name { t.Errorf("Unexpected name for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedName, apiRequestInfo.Name) } if !reflect.DeepEqual(successCase.expectedParts, apiRequestInfo.Parts) { t.Errorf("Unexpected parts for url: %s, expected: %v, actual: %v", successCase.url, successCase.expectedParts, apiRequestInfo.Parts) } } errorCases := map[string]string{ "no resource path": "/", "just apiversion": "/api/version/", "apiversion with no resource": "/api/version/", } for k, v := range errorCases { req, err := http.NewRequest("GET", v, nil) if err != nil { t.Errorf("Unexpected error %v", err) } _, err = apiRequestInfoResolver.GetAPIRequestInfo(req) if err == nil { t.Errorf("Expected error for key: %s", k) } } }
livingbio/kubernetes
pkg/apiserver/handlers_test.go
GO
apache-2.0
11,099
// Copyright 2011 Google Inc. All Rights Reserved. // This file was generated from .js source files by GYP. If you // want to make changes to this file you should either change the // javascript source files or the GYP script. #include "src/v8.h" #include "src/snapshot/natives.h" #include "src/utils.h" namespace v8 { namespace internal { static const char sources[] = { 10, 40, 102, 117, 110, 99, 116, 105, 111, 110, 32, 40, 103, 108, 111, 98, 97, 108, 44, 32, 98, 105, 110, 100, 105, 110, 103, 41, 32, 123, 10, 32, 32, 39, 117, 115, 101, 32, 115, 116, 114, 105, 99, 116, 39, 59, 10, 32, 32, 98, 105, 110, 100, 105, 110, 103, 46, 116, 101, 115, 116, 69, 120, 112, 101, 114, 105, 109, 101, 110, 116, 97, 108, 69, 120, 116, 114, 97, 83, 104, 111, 117, 108, 100, 82, 101, 116, 117, 114, 110, 84, 101, 110, 32, 61, 32, 102, 117, 110, 99, 116, 105, 111, 110, 32, 40, 41, 32, 123, 10, 32, 32, 32, 32, 114, 101, 116, 117, 114, 110, 32, 49, 48, 59, 10, 32, 32, 125, 59, 10, 32, 32, 98, 105, 110, 100, 105, 110, 103, 46, 116, 101, 115, 116, 69, 120, 112, 101, 114, 105, 109, 101, 110, 116, 97, 108, 69, 120, 116, 114, 97, 83, 104, 111, 117, 108, 100, 67, 97, 108, 108, 84, 111, 82, 117, 110, 116, 105, 109, 101, 32, 61, 32, 102, 117, 110, 99, 116, 105, 111, 110, 40, 41, 32, 123, 10, 32, 32, 32, 32, 114, 101, 116, 117, 114, 110, 32, 98, 105, 110, 100, 105, 110, 103, 46, 114, 117, 110, 116, 105, 109, 101, 40, 51, 41, 59, 10, 32, 32, 125, 59, 10, 125, 41, 10 }; template <> int NativesCollection<EXPERIMENTAL_EXTRAS>::GetBuiltinsCount() { return 1; } template <> int NativesCollection<EXPERIMENTAL_EXTRAS>::GetDebuggerCount() { return 0; } template <> int NativesCollection<EXPERIMENTAL_EXTRAS>::GetIndex(const char* name) { if (strcmp(name, "test-experimental-extra") == 0) return 0; return -1; } template <> Vector<const char> NativesCollection<EXPERIMENTAL_EXTRAS>::GetScriptSource(int index) { if (index == 0) return Vector<const char>(sources + 0, 235); return Vector<const char>("", 0); } template <> Vector<const char> NativesCollection<EXPERIMENTAL_EXTRAS>::GetScriptName(int index) { if (index == 0) return Vector<const char>("native test-experimental-extra.js", 33); return Vector<const char>("", 0); } template <> Vector<const char> NativesCollection<EXPERIMENTAL_EXTRAS>::GetScriptsSource() { return Vector<const char>(sources, 235); } } // internal } // v8
weolar/miniblink49
gen/v8_5_7/experimental-extras-libraries.cc
C++
apache-2.0
2,451
import java.util.*; class Test { private Set<String> foo; void test(Test t1, String s) { t1.foo = new HashSet<>(); t1.foo.add(s); } }
siosio/intellij-community
plugins/IntentionPowerPak/test/com/siyeh/ipp/collections/to_mutable_collection/FieldAssignment_after.java
Java
apache-2.0
151
/// <reference path='fourslash.ts' /> ////function functionOverload(); ////function functionOverload(test: string); ////function functionOverload(test?: string) { } ////functionOverload(/*functionOverload1*/); ////functionOverload(""/*functionOverload2*/); verify.signatureHelp( { marker: "functionOverload1", overloadsCount: 2, text: "functionOverload(): any", parameterCount: 0, }, { marker: "functionOverload2", overloadsCount: 2, text: "functionOverload(test: string): any", parameterName: "test", parameterSpan: "test: string", }, );
domchen/typescript-plus
tests/cases/fourslash/signatureHelpFunctionOverload.ts
TypeScript
apache-2.0
652
/* * Copyright 2010 the original author or 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 org.spockframework.runtime.condition; public interface IObjectRendererService extends IObjectRenderer<Object> { <T> void addRenderer(Class<T> type, IObjectRenderer<? super T> renderer); }
spockframework/spock
spock-core/src/main/java/org/spockframework/runtime/condition/IObjectRendererService.java
Java
apache-2.0
809
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.metadata; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.druid.jackson.DefaultObjectMapper; import io.druid.timeline.DataSegment; import io.druid.timeline.partition.LinearShardSpec; import org.joda.time.Interval; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.tweak.HandleCallback; import java.io.IOException; import java.util.Set; public class IndexerSQLMetadataStorageCoordinatorTest { private final MetadataStorageTablesConfig tablesConfig = MetadataStorageTablesConfig.fromBase("test"); private final TestDerbyConnector derbyConnector = new TestDerbyConnector( Suppliers.ofInstance(new MetadataStorageConnectorConfig()), Suppliers.ofInstance(tablesConfig) ); private final ObjectMapper mapper = new DefaultObjectMapper(); private final DataSegment defaultSegment = new DataSegment( "dataSource", Interval.parse("2015-01-01T00Z/2015-01-02T00Z"), "version", ImmutableMap.<String, Object>of(), ImmutableList.of("dim1"), ImmutableList.of("m1"), new LinearShardSpec(0), 9, 100 ); private final DataSegment defaultSegment2 = new DataSegment( "dataSource", Interval.parse("2015-01-01T00Z/2015-01-02T00Z"), "version", ImmutableMap.<String, Object>of(), ImmutableList.of("dim1"), ImmutableList.of("m1"), new LinearShardSpec(1), 9, 100 ); private final Set<DataSegment> segments = ImmutableSet.of(defaultSegment, defaultSegment2); IndexerSQLMetadataStorageCoordinator coordinator; @Before public void setUp() { mapper.registerSubtypes(LinearShardSpec.class); derbyConnector.createTaskTables(); derbyConnector.createSegmentTable(); coordinator = new IndexerSQLMetadataStorageCoordinator( mapper, tablesConfig, derbyConnector ); } @After public void tearDown() { derbyConnector.tearDown(); } private void unUseSegment() { for (final DataSegment segment : segments) { Assert.assertEquals( 1, (int) derbyConnector.getDBI().<Integer>withHandle( new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { return handle.createStatement( String.format("UPDATE %s SET used = false WHERE id = :id", tablesConfig.getSegmentsTable()) ) .bind("id", segment.getIdentifier()) .execute(); } } ) ); } } @Test public void testSimpleAnnounce() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertArrayEquals( mapper.writeValueAsString(defaultSegment).getBytes("UTF-8"), derbyConnector.lookup( tablesConfig.getSegmentsTable(), "id", "payload", defaultSegment.getIdentifier() ) ); } @Test public void testSimpleUsedList() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUsedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval() ) ) ); } @Test public void testSimpleUnUsedList() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval() ) ) ); } @Test public void testUsedOverlapLow() throws IOException { coordinator.announceHistoricalSegments(segments); Set<DataSegment> actualSegments = ImmutableSet.copyOf( coordinator.getUsedSegmentsForInterval( defaultSegment.getDataSource(), Interval.parse("2014-12-31T23:59:59.999Z/2015-01-01T00:00:00.001Z") // end is exclusive ) ); Assert.assertEquals( segments, actualSegments ); } @Test public void testUsedOverlapHigh() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUsedSegmentsForInterval( defaultSegment.getDataSource(), Interval.parse("2015-1-1T23:59:59.999Z/2015-02-01T00Z") ) ) ); } @Test public void testUsedOutOfBoundsLow() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertTrue( coordinator.getUsedSegmentsForInterval( defaultSegment.getDataSource(), new Interval(defaultSegment.getInterval().getStart().minus(1), defaultSegment.getInterval().getStart()) ).isEmpty() ); } @Test public void testUsedOutOfBoundsHigh() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertTrue( coordinator.getUsedSegmentsForInterval( defaultSegment.getDataSource(), new Interval(defaultSegment.getInterval().getEnd(), defaultSegment.getInterval().getEnd().plusDays(10)) ).isEmpty() ); } @Test public void testUsedWithinBoundsEnd() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUsedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().minusMillis(1)) ) ) ); } @Test public void testUsedOverlapEnd() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUsedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().plusMillis(1)) ) ) ); } @Test public void testUnUsedOverlapLow() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertTrue( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), new Interval( defaultSegment.getInterval().getStart().minus(1), defaultSegment.getInterval().getStart().plus(1) ) ).isEmpty() ); } @Test public void testUnUsedUnderlapLow() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertTrue( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), new Interval(defaultSegment.getInterval().getStart().plus(1), defaultSegment.getInterval().getEnd()) ).isEmpty() ); } @Test public void testUnUsedUnderlapHigh() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertTrue( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), new Interval(defaultSegment.getInterval().getStart(), defaultSegment.getInterval().getEnd().minus(1)) ).isEmpty() ); } @Test public void testUnUsedOverlapHigh() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertTrue( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval().withStart(defaultSegment.getInterval().getEnd().minus(1)) ).isEmpty() ); } @Test public void testUnUsedBigOverlap() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), Interval.parse("2000/2999") ) ) ); } @Test public void testUnUsedLowRange() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval().withStart(defaultSegment.getInterval().getStart().minus(1)) ) ) ); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval().withStart(defaultSegment.getInterval().getStart().minusYears(1)) ) ) ); } @Test public void testUnUsedHighRange() throws IOException { coordinator.announceHistoricalSegments(segments); unUseSegment(); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().plus(1)) ) ) ); Assert.assertEquals( segments, ImmutableSet.copyOf( coordinator.getUnusedSegmentsForInterval( defaultSegment.getDataSource(), defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().plusYears(1)) ) ) ); } }
elijah513/druid
server/src/test/java/io/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java
Java
apache-2.0
11,028
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectView.impl.nodes; import com.intellij.ide.IdeBundle; import com.intellij.ide.projectView.PresentationData; import com.intellij.ide.projectView.ProjectViewNode; import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.libraries.LibraryEx; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryType; import com.intellij.openapi.roots.libraries.PersistentLibraryKind; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class LibraryGroupNode extends ProjectViewNode<LibraryGroupElement> { public LibraryGroupNode(Project project, @NotNull LibraryGroupElement value, ViewSettings viewSettings) { super(project, value, viewSettings); } @Override @NotNull public Collection<AbstractTreeNode<?>> getChildren() { Module module = getValue().getModule(); ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); List<AbstractTreeNode<?>> children = new ArrayList<>(); OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (final OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)orderEntry; final Library library = libraryOrderEntry.getLibrary(); if (library == null) { continue; } final String libraryName = library.getName(); if (libraryName == null || libraryName.length() == 0) { addLibraryChildren(libraryOrderEntry, children, getProject(), this); } else { children.add(new NamedLibraryElementNode(getProject(), new NamedLibraryElement(module, libraryOrderEntry), getSettings())); } } else if (orderEntry instanceof JdkOrderEntry) { final JdkOrderEntry jdkOrderEntry = (JdkOrderEntry)orderEntry; final Sdk jdk = jdkOrderEntry.getJdk(); if (jdk != null) { children.add(new NamedLibraryElementNode(getProject(), new NamedLibraryElement(module, jdkOrderEntry), getSettings())); } } } return children; } public static void addLibraryChildren(LibraryOrSdkOrderEntry entry, List<? super AbstractTreeNode<?>> children, Project project, ProjectViewNode node) { final PsiManager psiManager = PsiManager.getInstance(project); VirtualFile[] files = entry instanceof LibraryOrderEntry ? getLibraryRoots((LibraryOrderEntry)entry) : entry.getRootFiles(OrderRootType.CLASSES); for (final VirtualFile file : files) { if (!file.isValid()) continue; if (file.isDirectory()) { final PsiDirectory psiDir = psiManager.findDirectory(file); if (psiDir == null) { continue; } children.add(new PsiDirectoryNode(project, psiDir, node.getSettings())); } else { final PsiFile psiFile = psiManager.findFile(file); if (psiFile == null) continue; children.add(new PsiFileNode(project, psiFile, node.getSettings())); } } } @Override public String getTestPresentation() { return "Libraries"; } @Override public boolean contains(@NotNull VirtualFile file) { final ProjectFileIndex index = ProjectRootManager.getInstance(getProject()).getFileIndex(); if (!index.isInLibrary(file)) { return false; } return someChildContainsFile(file, false); } @Override public void update(@NotNull PresentationData presentation) { presentation.setPresentableText(IdeBundle.message("node.projectview.libraries")); presentation.setIcon(PlatformIcons.LIBRARY_ICON); } @Override public boolean canNavigate() { return ProjectSettingsService.getInstance(myProject).canOpenModuleLibrarySettings(); } @Override public void navigate(final boolean requestFocus) { Module module = getValue().getModule(); ProjectSettingsService.getInstance(myProject).openModuleLibrarySettings(module); } public static VirtualFile @NotNull [] getLibraryRoots(@NotNull LibraryOrderEntry orderEntry) { Library library = orderEntry.getLibrary(); if (library == null) return VirtualFile.EMPTY_ARRAY; OrderRootType[] rootTypes = LibraryType.DEFAULT_EXTERNAL_ROOT_TYPES; if (library instanceof LibraryEx) { if (((LibraryEx)library).isDisposed()) return VirtualFile.EMPTY_ARRAY; PersistentLibraryKind<?> libKind = ((LibraryEx)library).getKind(); if (libKind != null) { rootTypes = LibraryType.findByKind(libKind).getExternalRootTypes(); } } final ArrayList<VirtualFile> files = new ArrayList<>(); for (OrderRootType rootType : rootTypes) { files.addAll(Arrays.asList(library.getFiles(rootType))); } return VfsUtilCore.toVirtualFileArray(files); } }
siosio/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/LibraryGroupNode.java
Java
apache-2.0
5,590
/** * @fileoverview Rule to enforce spacing around embedded expressions of template strings * @author Toru Nagashima */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const OPEN_PAREN = /\$\{$/u; const CLOSE_PAREN = /^\}/u; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "layout", docs: { description: "require or disallow spacing around embedded expressions of template strings", category: "ECMAScript 6", recommended: false, url: "https://eslint.org/docs/rules/template-curly-spacing" }, fixable: "whitespace", schema: [ { enum: ["always", "never"] } ], messages: { expectedBefore: "Expected space(s) before '}'.", expectedAfter: "Expected space(s) after '${'.", unexpectedBefore: "Unexpected space(s) before '}'.", unexpectedAfter: "Unexpected space(s) after '${'." } }, create(context) { const sourceCode = context.getSourceCode(); const always = context.options[0] === "always"; const prefix = always ? "expected" : "unexpected"; /** * Checks spacing before `}` of a given token. * @param {Token} token A token to check. This is a Template token. * @returns {void} */ function checkSpacingBefore(token) { const prevToken = sourceCode.getTokenBefore(token); if (prevToken && CLOSE_PAREN.test(token.value) && astUtils.isTokenOnSameLine(prevToken, token) && sourceCode.isSpaceBetweenTokens(prevToken, token) !== always ) { context.report({ loc: token.loc.start, messageId: `${prefix}Before`, fix(fixer) { if (always) { return fixer.insertTextBefore(token, " "); } return fixer.removeRange([ prevToken.range[1], token.range[0] ]); } }); } } /** * Checks spacing after `${` of a given token. * @param {Token} token A token to check. This is a Template token. * @returns {void} */ function checkSpacingAfter(token) { const nextToken = sourceCode.getTokenAfter(token); if (nextToken && OPEN_PAREN.test(token.value) && astUtils.isTokenOnSameLine(token, nextToken) && sourceCode.isSpaceBetweenTokens(token, nextToken) !== always ) { context.report({ loc: { line: token.loc.end.line, column: token.loc.end.column - 2 }, messageId: `${prefix}After`, fix(fixer) { if (always) { return fixer.insertTextAfter(token, " "); } return fixer.removeRange([ token.range[1], nextToken.range[0] ]); } }); } } return { TemplateElement(node) { const token = sourceCode.getFirstToken(node); checkSpacingBefore(token); checkSpacingAfter(token); } }; } };
BigBoss424/portfolio
v8/development/node_modules/gatsby/node_modules/eslint/lib/rules/template-curly-spacing.js
JavaScript
apache-2.0
4,149
# Copyright (c) 2017 Keith Ito """ from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. ''' from . import cmudict _pad = '_' _punctuation = '!\'(),.:;? ' _special = '-' _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' # Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters): _arpabet = ['@' + s for s in cmudict.valid_symbols] # Export all symbols: symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters) + _arpabet
mlperf/inference_results_v0.7
open/Inspur/code/rnnt/tensorrt/preprocessing/parts/text/symbols.py
Python
apache-2.0
749
/* * 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.camel.component.jms; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import org.apache.camel.CamelContext; import org.apache.camel.CamelExecutionException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Test; import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; /** * */ public class JmsAllowNullBodyTest extends CamelTestSupport { @Test public void testAllowNullBodyDefault() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").message(0).body().isNull(); getMockEndpoint("mock:result").message(0).header("bar").isEqualTo(123); // allow null body is default enabled template.sendBodyAndHeader("activemq:queue:foo", null, "bar", 123); assertMockEndpointsSatisfied(); } @Test public void testAllowNullBody() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").message(0).body().isNull(); getMockEndpoint("mock:result").message(0).header("bar").isEqualTo(123); template.sendBodyAndHeader("activemq:queue:foo?allowNullBody=true", null, "bar", 123); assertMockEndpointsSatisfied(); } @Test public void testAllowNullTextBody() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").message(0).body().isNull(); getMockEndpoint("mock:result").message(0).header("bar").isEqualTo(123); template.sendBodyAndHeader("activemq:queue:foo?allowNullBody=true&jmsMessageType=Text", null, "bar", 123); assertMockEndpointsSatisfied(); } @Test public void testNoAllowNullBody() throws Exception { try { template.sendBodyAndHeader("activemq:queue:foo?allowNullBody=false", null, "bar", 123); fail("Should have thrown exception"); } catch (CamelExecutionException e) { JMSException cause = assertIsInstanceOf(JMSException.class, e.getCause().getCause()); assertEquals("Cannot send message as message body is null, and option allowNullBody is false.", cause.getMessage()); } } @Override protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("activemq:queue:foo").to("mock:result"); } }; } }
nikhilvibhav/camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsAllowNullBodyTest.java
Java
apache-2.0
3,981
/* * * 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. * */ var server = {}; (function (server) { var USER = 'server.user'; var log = new Log(); /** * Returns the currently logged in user */ server.current = function (session, user) { if (arguments.length > 1) { session.put(USER, user); return user; } return session.get(USER); }; }(server));
hsbhathiya/stratos
components/org.apache.stratos.manager.console/modules/console/scripts/server.js
JavaScript
apache-2.0
1,188
package graph import ( "fmt" "io" "runtime" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" "github.com/docker/docker/utils" ) // Lookup looks up an image by name in a TagStore and returns it as an // ImageInspect structure. func (s *TagStore) Lookup(name string) (*types.ImageInspect, error) { image, err := s.LookupImage(name) if err != nil || image == nil { return nil, fmt.Errorf("No such image: %s", name) } var tags = make([]string, 0) s.Lock() for repoName, repository := range s.Repositories { for ref, id := range repository { if id == image.ID { imgRef := utils.ImageReference(repoName, ref) tags = append(tags, imgRef) } } } s.Unlock() imageInspect := &types.ImageInspect{ ID: image.ID, Tags: tags, Parent: image.Parent, Comment: image.Comment, Created: image.Created.Format(time.RFC3339Nano), Container: image.Container, ContainerConfig: &image.ContainerConfig, DockerVersion: image.DockerVersion, Author: image.Author, Config: image.Config, Architecture: image.Architecture, Os: image.OS, Size: image.Size, VirtualSize: s.graph.GetParentsSize(image) + image.Size, } imageInspect.GraphDriver.Name = s.graph.driver.String() graphDriverData, err := s.graph.driver.GetMetadata(image.ID) if err != nil { return nil, err } imageInspect.GraphDriver.Data = graphDriverData return imageInspect, nil } // ImageTarLayer return the tarLayer of the image func (s *TagStore) ImageTarLayer(name string, dest io.Writer) error { if image, err := s.LookupImage(name); err == nil && image != nil { // On Windows, the base layer cannot be exported if runtime.GOOS != "windows" || image.Parent != "" { fs, err := s.graph.TarLayer(image) if err != nil { return err } defer fs.Close() written, err := io.Copy(dest, fs) if err != nil { return err } logrus.Debugf("rendered layer for %s of [%d] size", image.ID, written) } return nil } return fmt.Errorf("No such image: %s", name) }
wcwxyz/docker
graph/service.go
GO
apache-2.0
2,129
/* * #%L * Native ARchive plugin for Maven * %% * Copyright (C) 2002 - 2014 NAR Maven Plugin developers. * %% * 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. * #L% */ package com.github.maven_nar.cpptasks.compiler; import java.io.File; import org.apache.tools.ant.BuildException; import com.github.maven_nar.cpptasks.CCTask; import com.github.maven_nar.cpptasks.CompilerDef; import com.github.maven_nar.cpptasks.ProcessorDef; import com.github.maven_nar.cpptasks.VersionInfo; import com.github.maven_nar.cpptasks.parser.CParser; import com.github.maven_nar.cpptasks.parser.Parser; /** * Test for abstract compiler class * * Override create to test concrete compiler implementions */ public class TestAbstractCompiler extends TestAbstractProcessor { private class DummyAbstractCompiler extends AbstractCompiler { public DummyAbstractCompiler() { super(new String[] { ".cpp", ".c" }, new String[] { ".hpp", ".h", ".inl" }, ".o"); } public void compile(final CCTask task, final File[] srcfile, final File[] outputfile, final CompilerConfiguration config) throws BuildException { throw new BuildException("Not implemented"); } @Override public CompilerConfiguration createConfiguration(final CCTask task, final LinkType linkType, final ProcessorDef[] def1, final CompilerDef def2, final com.github.maven_nar.cpptasks.TargetDef targetPlatform, final VersionInfo versionInfo) { return null; } @Override public Parser createParser(final File file) { return new CParser(); } @Override public String getIdentifier() { return "dummy"; } @Override public Linker getLinker(final LinkType type) { return null; } } public TestAbstractCompiler(final String name) { super(name); } @Override protected AbstractProcessor create() { return new DummyAbstractCompiler(); } public void failingtestGetOutputFileName1() { final AbstractProcessor compiler = create(); String[] output = compiler.getOutputFileNames("c:/foo\\bar\\hello.c", null); assertEquals("hello" + getObjectExtension(), output[0]); output = compiler.getOutputFileNames("c:/foo\\bar/hello.c", null); assertEquals("hello" + getObjectExtension(), output[0]); output = compiler.getOutputFileNames("hello.c", null); assertEquals("hello" + getObjectExtension(), output[0]); output = compiler.getOutputFileNames("c:/foo\\bar\\hello.h", null); assertEquals(0, output.length); output = compiler.getOutputFileNames("c:/foo\\bar/hello.h", null); assertEquals(0, output.length); } protected String getObjectExtension() { return ".o"; } public void testCanParseTlb() { final AbstractCompiler compiler = (AbstractCompiler) create(); assertEquals(false, compiler.canParse(new File("sample.tlb"))); } }
dugilos/nar-maven-plugin
src/test/java/com/github/maven_nar/cpptasks/compiler/TestAbstractCompiler.java
Java
apache-2.0
3,408
/// <reference path='fourslash.ts' /> // @Filename: goToTypeDefinitioAliases_module1.ts /////*definition*/interface I { //// p; ////} ////export {I as I2}; // @Filename: goToTypeDefinitioAliases_module2.ts ////import {I2 as I3} from "./goToTypeDefinitioAliases_module1"; ////var v1: I3; ////export {v1 as v2}; // @Filename: goToTypeDefinitioAliases_module3.ts ////import {/*reference1*/v2 as v3} from "./goToTypeDefinitioAliases_module2"; /////*reference2*/v3; goTo.marker('reference1'); goTo.type(); verify.caretAtMarker('definition'); goTo.marker('reference2'); goTo.type(); verify.caretAtMarker('definition');
plantain-00/TypeScript
tests/cases/fourslash/goToTypeDefinitionAliases.ts
TypeScript
apache-2.0
645
/* * 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.camel.component.redis; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit5.CamelTestSupport; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoSettings; import org.springframework.data.redis.core.RedisTemplate; @MockitoSettings public class RedisTestSupport extends CamelTestSupport { @Mock protected RedisTemplate<String, String> redisTemplate; @Produce("direct:start") protected ProducerTemplate template; @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start") .to("spring-redis://localhost:6379?redisTemplate=#redisTemplate"); } }; } protected Object sendHeaders(final Object... headers) { Exchange exchange = template.send(new Processor() { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); for (int i = 0; i < headers.length; i = i + 2) { in.setHeader(headers[i].toString(), headers[i + 1]); } } }); return exchange.getIn().getBody(); } }
tdiesler/camel
components/camel-spring-redis/src/test/java/org/apache/camel/component/redis/RedisTestSupport.java
Java
apache-2.0
2,242
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_espn_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(5) class SkiaEspnDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaEspnDesktopPageSet, self).__init__( archive_data_file='data/skia_espn_desktop.json') urls_list = [ # Why: #1 sports. 'http://espn.go.com', ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
HalCanary/skia-hc
tools/skp/page_sets/skia_espn_desktop.py
Python
bsd-3-clause
1,170
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_dialogs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "net/test/embedded_test_server/embedded_test_server.h" typedef InProcessBrowserTest CollectedCookiesTest; // If this crashes on Windows, use http://crbug.com/79331 IN_PROC_BROWSER_TEST_F(CollectedCookiesTest, DoubleDisplay) { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); // Disable cookies. CookieSettingsFactory::GetForProfile(browser()->profile()) ->SetDefaultCookieSetting(CONTENT_SETTING_BLOCK); // Load a page with cookies. ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/cookie1.html")); // Click on the info link twice. content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); TabDialogs::FromWebContents(web_contents)->ShowCollectedCookies(); TabDialogs::FromWebContents(web_contents)->ShowCollectedCookies(); } // If this crashes on Windows, use http://crbug.com/79331 IN_PROC_BROWSER_TEST_F(CollectedCookiesTest, NavigateAway) { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); // Disable cookies. CookieSettingsFactory::GetForProfile(browser()->profile()) ->SetDefaultCookieSetting(CONTENT_SETTING_BLOCK); // Load a page with cookies. ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/cookie1.html")); // Click on the info link. content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); TabDialogs::FromWebContents(web_contents)->ShowCollectedCookies(); // Navigate to another page. ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/cookie2.html")); }
SaschaMester/delicium
chrome/browser/collected_cookies_browsertest.cc
C++
bsd-3-clause
2,289
var get = Ember.get; Ember._ResolvedState = Ember.Object.extend({ manager: null, state: null, match: null, object: Ember.computed(function(key) { if (this._object) { return this._object; } else { var state = get(this, 'state'), match = get(this, 'match'), manager = get(this, 'manager'); return state.deserialize(manager, match.hash); } }), hasPromise: Ember.computed(function() { return Ember.canInvoke(get(this, 'object'), 'then'); }).property('object'), promise: Ember.computed(function() { var object = get(this, 'object'); if (Ember.canInvoke(object, 'then')) { return object; } else { return { then: function(success) { success(object); } }; } }).property('object'), transition: function() { var manager = get(this, 'manager'), path = get(this, 'state.path'), object = get(this, 'object'); manager.transitionTo(path, object); } });
teddyzeenny/ember.js
packages/ember-old-router/lib/resolved_state.js
JavaScript
mit
985
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Orleans; using Orleans.Concurrency; using System.Threading.Tasks; namespace TwitterGrainInterfaces { /// <summary> /// A grain to act as the API into Orleans, and fan out read/writes to multiple hashtag grains /// </summary> public interface ITweetDispatcherGrain : IGrainWithIntegerKey { Task AddScore(int score, string[] hashtags, string tweet); Task<Totals[]> GetTotals(string[] hashtags); } }
TedDBarr/orleans
Samples/TwitterSentiment/TwitterGrainInterfaces/ITweetGrain.cs
C#
mit
1,600
require('mocha'); require('should'); var assert = require('assert'); var support = require('./support'); var App = support.resolve(); var app; describe('app.option', function() { beforeEach(function() { app = new App(); }); it('should set a key-value pair on options:', function() { app.option('a', 'b'); assert(app.options.a === 'b'); }); it('should set an object on options:', function() { app.option({c: 'd'}); assert(app.options.c === 'd'); }); it('should set an option.', function() { app.option('a', 'b'); app.options.should.have.property('a'); }); it('should get an option.', function() { app.option('a', 'b'); app.option('a').should.equal('b'); }); it('should extend the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.option('x').should.equal('xxx'); app.option('y').should.equal('yyy'); app.option('z').should.equal('zzz'); }); it('options should be on the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.options.x.should.equal('xxx'); app.options.y.should.equal('yyy'); app.options.z.should.equal('zzz'); }); it('should be chainable.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.option({a: 'aaa', b: 'bbb', c: 'ccc'}); app.option('x').should.equal('xxx'); app.option('a').should.equal('aaa'); }); it('should extend the `options` object when the first param is a string.', function() { app.option('foo', {x: 'xxx', y: 'yyy', z: 'zzz'}); app.option('bar', {a: 'aaa', b: 'bbb', c: 'ccc'}); app.option('foo').should.have.property('x'); app.option('bar').should.have.property('a'); app.options.foo.should.have.property('x'); app.options.bar.should.have.property('a'); }); it('should set an option.', function() { app.option('a', 'b'); app.options.should.have.property('a'); }); it('should get an option.', function() { app.option('a', 'b'); app.option('a').should.equal('b'); }); it('should extend the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.option('x').should.equal('xxx'); app.option('y').should.equal('yyy'); app.option('z').should.equal('zzz'); }); it('options should be on the `options` object.', function() { app.option({x: 'xxx', y: 'yyy', z: 'zzz'}); app.options.x.should.equal('xxx'); app.options.y.should.equal('yyy'); app.options.z.should.equal('zzz'); }); it('should be chainable.', function() { app .option({x: 'xxx', y: 'yyy', z: 'zzz'}) .option({a: 'aaa', b: 'bbb', c: 'ccc'}); app.option('x').should.equal('xxx'); app.option('a').should.equal('aaa'); }); });
Gargitier5/tier5portal
vendors/update/test/app.option.js
JavaScript
mit
2,760
# encoding: utf-8 module Mongoid #:nodoc: module Extensions #:nodoc: module Boolean #:nodoc: module Conversions #:nodoc: def set(value) val = value.to_s val == "true" || val == "1" end def get(value) value end end end end end
listrophy/mongoid
lib/mongoid/extensions/boolean/conversions.rb
Ruby
mit
312
<?php class Foo extends Bar { public function bar($foobar = array(parent::FOOBAR)) {} } ?>
sowbiba/senegal-front
vendor/pdepend/pdepend/src/test/resources/files/Parser/testParserHandlesParentKeywordInMethodParameterDefaultValue.php
PHP
mit
95
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['mn.', 'mg.', 'fm.', 'em.', 'kv.', 'nt.'], ['midn.', 'morg.', 'form.', 'etterm.', 'kveld', 'natt'], ['midnatt', 'morgenen', 'formiddagen', 'ettermiddagen', 'kvelden', 'natten'] ], [ ['mn.', 'mg.', 'fm.', 'em.', 'kv.', 'nt.'], ['midn.', 'morg.', 'form.', 'etterm.', 'kveld', 'natt'], ['midnatt', 'morgen', 'formiddag', 'ettermiddag', 'kveld', 'natt'] ], [ '00:00', ['06:00', '10:00'], ['10:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'], ['00:00', '06:00'] ] ];
mgechev/angular
packages/common/locales/extra/nb.ts
TypeScript
mit
848
<?php /** * Settings screen sidebar for free plugins with a pro version. Display the reasons to upgrade * and the mailing list. */ ?> <!-- Keep Updated --> <div class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span><?php _e('Keep Updated', $this->plugin->name); ?></span></h3> <div class="option"> <p class="description"><?php _e('Subscribe to the newsletter and receive updates on our WordPress Plugins', $this->plugin->name); ?>.</p> </div> <form action="http://n7studios.createsend.com/t/r/s/jdutdyj/" method="post"> <div class="option"> <p> <strong><?php _e('Email', $this->plugin->name); ?></strong> <input id="fieldEmail" name="cm-jdutdyj-jdutdyj" type="email" required /> </p> </div> <div class="option"> <p> <input type="submit" name="submit" value="<?php _e('Subscribe', $this->plugin->name); ?>" class="button button-primary" /> </p> </div> </form> </div>
TheOrchardSolutions/WordPress
wp-content/plugins/wp-to-buffer/_modules/dashboard/views/sidebar-upgrade.php
PHP
gpl-2.0
1,049
// SPDX-License-Identifier: GPL-2.0-or-later package org.dolphinemu.dolphinemu.adapters; import android.content.res.Resources; import android.view.ViewGroup; import androidx.leanback.widget.ImageCardView; import androidx.leanback.widget.Presenter; import org.dolphinemu.dolphinemu.model.TvSettingsItem; import org.dolphinemu.dolphinemu.viewholders.TvSettingsViewHolder; public final class SettingsRowPresenter extends Presenter { public Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) { // Create a new view. ImageCardView settingsCard = new ImageCardView(parent.getContext()); settingsCard.setMainImageAdjustViewBounds(true); settingsCard.setMainImageDimensions(192, 160); settingsCard.setFocusable(true); settingsCard.setFocusableInTouchMode(true); // Use that view to create a ViewHolder. return new TvSettingsViewHolder(settingsCard); } public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) { TvSettingsViewHolder holder = (TvSettingsViewHolder) viewHolder; TvSettingsItem settingsItem = (TvSettingsItem) item; Resources resources = holder.cardParent.getResources(); holder.itemId = settingsItem.getItemId(); holder.cardParent.setTitleText(resources.getString(settingsItem.getLabelId())); holder.cardParent.setMainImage(resources.getDrawable(settingsItem.getIconId(), null)); } public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) { // no op } }
ZephyrSurfer/dolphin
Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/adapters/SettingsRowPresenter.java
Java
gpl-2.0
1,484
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /* * This file is based on WME Lite. * http://dead-code.org/redir.php?target=wmelite * Copyright (c) 2011 Jan Nedoma */ #include "engines/wintermute/base/base_game.h" #include "engines/wintermute/base/base_scriptable.h" #include "engines/wintermute/base/scriptables/script.h" #include "engines/wintermute/base/scriptables/script_value.h" #include "engines/wintermute/base/scriptables/script_stack.h" namespace Wintermute { bool EmulateHTTPConnectExternalCalls(BaseGame *inGame, ScStack *stack, ScStack *thisStack, ScScript::TExternalFunction *function) { ////////////////////////////////////////////////////////////////////////// // Register // Used to register license key online at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Specification: external "httpconnect.dll" cdecl long Register(string, long, string, long) // Known usage: Register(<productId>, 65535, <productKey>, 65535) // Known product ID values are: "357868", "353058" and "353006" // Known action: HTTP GET http://keygen.corbomitegames.com/keygen/validateKey.php?action=REGISTER&productId=productId&key=productKey // Returns 1 on success // Returns 0 on firewall error // Returns -1 on invalid product key // Returns -2 on invalid product ID // Returns -3 on expired product key // Returns -4 on invalid machine ID // Returns -5 on number of installations exceeded // Returns -6 on socket error // Returns -7 on no internet connection // Returns -8 on connection reset // Returns -11 on validation temporary unavaliable // Returns -12 on validation error // For some reason always returns -7 for me in a test game ////////////////////////////////////////////////////////////////////////// if (strcmp(function->name, "Register") == 0) { stack->correctParams(4); const char *productId = stack->pop()->getString(); int productIdMaxLen = stack->pop()->getInt(); const char *productKey = stack->pop()->getString(); int productKeyMaxLen = stack->pop()->getInt(); warning("Register(\"%s\",%d,\"%s\",%d) is not implemented", productId , productIdMaxLen, productKey, productKeyMaxLen); stack->pushInt(-7); // "no internet connection" error return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // Validate // Used to validate something at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Specification: external "httpconnect.dll" cdecl long Validate() // Known usage: Validate() // Known action: HTTP GET http://keygen.corbomitegames.com/keygen/validateKey.php?action=VALIDATE&productId=Ar&key=Ar // Used only when Debug mode is active or game is started with "INVALID" cmdline parameter // For some reason always returns 1 for me in a test game ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "Validate") == 0) { stack->correctParams(0); // do nothing stack->pushInt(1); return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // SendHTTPAsync // Used to send game progress events to server at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Specification: external "httpconnect.dll" cdecl long SendHTTPAsync(string, long, string, long, string, long) // Known usage: SendHTTPAsync("backend.pizzamorgana.com", 65535, <FullURL>, 65535, <Buffer?!>, 65535) // FullURL is formed as "http://backend.pizzamorgana.com/event.php?Event=<EventName>&player=<PlayerName>&extraParams=<ExtraParams>&SN=<ProductKey>&Episode=1&GameTime=<CurrentTime>&UniqueID=<UniqueId>" // Known EventName values are: "GameStart", "ChangeGoal", "EndGame" and "QuitGame" // Known ExtraParams values are: "ACT0", "ACT1", "ACT2", "ACT3", "ACT4", "Ep0FindFood", "Ep0FindCellMenu", "Ep0BroRoom", "Ep0FindKey", "Ep0FindCellMenuKey", "Ep0FindMenuKey", "Ep0FindCell", "Ep0FindMenu", "Ep0OrderPizza", "Ep0GetRidOfVamp", "Ep0GetVampAttention", "Ep0License" // Return value is never used ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "SendHTTPAsync") == 0) { stack->correctParams(6); const char *server = stack->pop()->getString(); int serverMaxLen = stack->pop()->getInt(); const char *fullUrl = stack->pop()->getString(); int fullUrlMaxLen = stack->pop()->getInt(); const char *param5 = stack->pop()->getString(); int param5MaxLen = stack->pop()->getInt(); // TODO: Maybe parse URL and call some Achievements API using ExtraParams values in some late future warning("SendHTTPAsync(\"%s\",%d,\"%s\",%d,\"%s\",%d) is not implemented", server, serverMaxLen, fullUrl, fullUrlMaxLen, param5, param5MaxLen); stack->pushInt(0); return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // SendRecvHTTP (6 params variant) // Declared at Pizza Morgana: Episode 1 - Monsters and Manipulations in the Magical Forest // Seems to be unused, probably SendRecvHTTP was initially used instead of SendHTTPAsync // Specification: external "httpconnect.dll" cdecl long SendRecvHTTP(string, long, string, long, string, long) // Always returns -7 for me in a test game, probably returns the same network errors as Register() ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "SendRecvHTTP") == 0 && function->nu_params == 6) { stack->correctParams(6); const char *server = stack->pop()->getString(); int serverMaxLen = stack->pop()->getInt(); const char *fullUrl = stack->pop()->getString(); int fullUrlMaxLen = stack->pop()->getInt(); const char *param5 = stack->pop()->getString(); int param5MaxLen = stack->pop()->getInt(); warning("SendRecvHTTP(\"%s\",%d,\"%s\",%d,\"%s\",%d) is not implemented", server, serverMaxLen, fullUrl, fullUrlMaxLen, param5, param5MaxLen); stack->pushInt(-7); // "no internet connection" error return STATUS_OK; } ////////////////////////////////////////////////////////////////////////// // SendRecvHTTP (4 params variant) // Used to call HTTP methods at Zbang! The Game // Specification: external "httpconnect.dll" cdecl long SendRecvHTTP(string, long, string, long) // Known usage: SendRecvHTTP("scoresshort.php?player=<PlayerName>", 65535, <Buffer>, 65535) // Known usage: SendRecvHTTP("/update.php?player=<PlayerName>&difficulty=<Difficulty>&items=<CommaSeparatedItemList>", 65535, <Buffer>, 65535) // My Zbang demo does not have this dll, so there is no way to actually test it with a test game // Return value is never used in Zbang scripts ////////////////////////////////////////////////////////////////////////// else if (strcmp(function->name, "SendRecvHTTP") == 0 && function->nu_params == 4) { stack->correctParams(4); const char *dirUrl = stack->pop()->getString(); int dirUrlMaxLen = stack->pop()->getInt(); /*ScValue *buf =*/ stack->pop(); int bufMaxLen = stack->pop()->getInt(); //TODO: Count items and give scores, persist those values warning("SendRecvHTTP(\"%s\",%d,buf,%d) is not implemented", dirUrl, dirUrlMaxLen, bufMaxLen); stack->pushInt(0); return STATUS_OK; } return STATUS_FAILED; } } // End of namespace Wintermute
somaen/scummvm
engines/wintermute/ext/dll_httpconnect.cpp
C++
gpl-2.0
8,196
// errorcheck // Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Issue 20227: panic while constructing constant "1i/1e-600000000" package p var _ = 1 / 1e-600000000i // ERROR "division by zero" var _ = 1i / 1e-600000000 // ERROR "division by zero" var _ = 1i / 1e-600000000i // ERROR "division by zero" var _ = 1 / (1e-600000000 + 1e-600000000i) // ERROR "division by zero" var _ = 1i / (1e-600000000 + 1e-600000000i) // ERROR "division by zero"
Gurgel100/gcc
gcc/testsuite/go.test/test/fixedbugs/issue20227.go
GO
gpl-2.0
565
<?php // $Id: panels-dashboard-link.tpl.php,v 1.3 2010/10/11 22:56:02 sdboyer Exp $ ?> <div class="dashboard-entry clearfix"> <div class="dashboard-text"> <div class="dashboard-link"> <?php print $link['title']; ?> </div> <div class="description"> <?php print $link['description']; ?> </div> </div> </div>
TransmissionStudios/Transmission
sites/default/modules/panels/templates/panels-dashboard-link.tpl.php
PHP
gpl-2.0
338
tinyMCE.addI18n('ka.wordcount',{words:"Words: "});
freaxmind/miage-l3
web/blog Tim Burton/tim_burton/protected/extensions/tinymce/assets/tiny_mce/plugins/wordc/langs/ka_dlg.js
JavaScript
gpl-3.0
50
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2015 Daniel Marjamäki and Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QObject> #include <QString> #include <QList> #include <QDir> #include <QXmlStreamWriter> #include <QDebug> #include "report.h" #include "erroritem.h" #include "xmlreport.h" #include "xmlreportv1.h" static const char ResultElementName[] = "results"; static const char ErrorElementName[] = "error"; static const char FilenameAttribute[] = "file"; static const char LineAttribute[] = "line"; static const char IdAttribute[] = "id"; static const char SeverityAttribute[] = "severity"; static const char MsgAttribute[] = "msg"; XmlReportV1::XmlReportV1(const QString &filename) : XmlReport(filename), mXmlReader(NULL), mXmlWriter(NULL) { } XmlReportV1::~XmlReportV1() { delete mXmlReader; delete mXmlWriter; } bool XmlReportV1::Create() { if (Report::Create()) { mXmlWriter = new QXmlStreamWriter(Report::GetFile()); return true; } return false; } bool XmlReportV1::Open() { if (Report::Open()) { mXmlReader = new QXmlStreamReader(Report::GetFile()); return true; } return false; } void XmlReportV1::WriteHeader() { mXmlWriter->setAutoFormatting(true); mXmlWriter->writeStartDocument(); mXmlWriter->writeStartElement(ResultElementName); } void XmlReportV1::WriteFooter() { mXmlWriter->writeEndElement(); mXmlWriter->writeEndDocument(); } void XmlReportV1::WriteError(const ErrorItem &error) { /* Error example from the core program in xml <error file="gui/test.cpp" line="14" id="mismatchAllocDealloc" severity="error" msg="Mismatching allocation and deallocation: k"/> The callstack seems to be ignored here as well, instead last item of the stack is used */ // Don't write inconclusive errors to XML V1 if (error.inconclusive) return; mXmlWriter->writeStartElement(ErrorElementName); QString file = QDir::toNativeSeparators(error.files[error.files.size() - 1]); file = XmlReport::quoteMessage(file); mXmlWriter->writeAttribute(FilenameAttribute, file); const QString line = QString::number(error.lines[error.lines.size() - 1]); mXmlWriter->writeAttribute(LineAttribute, line); mXmlWriter->writeAttribute(IdAttribute, error.errorId); // Don't localize severity so we can read these files mXmlWriter->writeAttribute(SeverityAttribute, GuiSeverity::toString(error.severity)); const QString message = XmlReport::quoteMessage(error.message); mXmlWriter->writeAttribute(MsgAttribute, message); mXmlWriter->writeEndElement(); } QList<ErrorItem> XmlReportV1::Read() { QList<ErrorItem> errors; bool insideResults = false; if (!mXmlReader) { qDebug() << "You must Open() the file before reading it!"; return errors; } while (!mXmlReader->atEnd()) { switch (mXmlReader->readNext()) { case QXmlStreamReader::StartElement: if (mXmlReader->name() == ResultElementName) insideResults = true; // Read error element from inside result element if (insideResults && mXmlReader->name() == ErrorElementName) { ErrorItem item = ReadError(mXmlReader); errors.append(item); } break; case QXmlStreamReader::EndElement: if (mXmlReader->name() == ResultElementName) insideResults = false; break; // Not handled case QXmlStreamReader::NoToken: case QXmlStreamReader::Invalid: case QXmlStreamReader::StartDocument: case QXmlStreamReader::EndDocument: case QXmlStreamReader::Characters: case QXmlStreamReader::Comment: case QXmlStreamReader::DTD: case QXmlStreamReader::EntityReference: case QXmlStreamReader::ProcessingInstruction: break; } } return errors; } ErrorItem XmlReportV1::ReadError(QXmlStreamReader *reader) { ErrorItem item; if (reader->name().toString() == ErrorElementName) { QXmlStreamAttributes attribs = reader->attributes(); QString file = attribs.value("", FilenameAttribute).toString(); file = XmlReport::unquoteMessage(file); item.file = file; item.files.push_back(file); const int line = attribs.value("", LineAttribute).toString().toUInt(); item.lines.push_back(line); item.errorId = attribs.value("", IdAttribute).toString(); item.severity = GuiSeverity::fromString(attribs.value("", SeverityAttribute).toString()); // NOTE: This duplicates the message to Summary-field. But since // old XML format doesn't have separate summary and verbose messages // we must add same message to both data so it shows up in GUI. // Check if there is full stop and cut the summary to it. QString summary = attribs.value("", MsgAttribute).toString(); const int ind = summary.indexOf('.'); if (ind != -1) summary = summary.left(ind + 1); item.summary = XmlReport::unquoteMessage(summary); QString message = attribs.value("", MsgAttribute).toString(); item.message = XmlReport::unquoteMessage(message); } return item; }
SkyroverTech/SkyroverCF
lib/cppcheck-1.71/gui/xmlreportv1.cpp
C++
gpl-3.0
5,973
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; namespace ICSharpCode.ILSpy.Debugger.Services { /// <summary> /// Very naive parser. /// </summary> static class ParserService { static HashSet<string> mySet = new HashSet<string>(); static ParserService() { mySet.AddRange((new string [] { ".", "{", "}", "(", ")", "[", "]", " ", "=", "+", "-", "/", "%", "*", "&", Environment.NewLine, ";", ",", "~", "!", "?", @"\n", @"\t", @"\r", "|" })); } static void AddRange<T>(this ICollection<T> list, IEnumerable<T> items) { foreach (T item in items) if (!list.Contains(item)) list.Add(item); } /// <summary> /// Returns the variable name /// </summary> /// <param name="fullText"></param> /// <param name="offset"></param> /// <returns></returns> public static string SimpleParseAt(string fullText, int offset) { if (string.IsNullOrEmpty(fullText)) return string.Empty; if (offset <= 0 || offset >= fullText.Length) return string.Empty; string currentValue = fullText[offset].ToString(); if (mySet.Contains(currentValue)) return string.Empty; int left = offset, right = offset; //search left while((!mySet.Contains(currentValue) || currentValue == ".") && left > 0) currentValue = fullText[--left].ToString(); currentValue = fullText[offset].ToString(); // searh right while(!mySet.Contains(currentValue) && right < fullText.Length - 2) currentValue = fullText[++right].ToString(); return fullText.Substring(left + 1, right - 1 - left).Trim(); } } }
damnya/dnSpy
ILSpy/Services/ParserService.cs
C#
gpl-3.0
2,300
// This file has been generated by Py++. #include "boost/python.hpp" #include "generators/include/python_CEGUI.h" #include "DefaultLogger.pypp.hpp" namespace bp = boost::python; struct DefaultLogger_wrapper : CEGUI::DefaultLogger, bp::wrapper< CEGUI::DefaultLogger > { DefaultLogger_wrapper( ) : CEGUI::DefaultLogger( ) , bp::wrapper< CEGUI::DefaultLogger >(){ // null constructor } virtual void logEvent( ::CEGUI::String const & message, ::CEGUI::LoggingLevel level=::CEGUI::Standard ) { if( bp::override func_logEvent = this->get_override( "logEvent" ) ) func_logEvent( boost::ref(message), level ); else{ this->CEGUI::DefaultLogger::logEvent( boost::ref(message), level ); } } void default_logEvent( ::CEGUI::String const & message, ::CEGUI::LoggingLevel level=::CEGUI::Standard ) { CEGUI::DefaultLogger::logEvent( boost::ref(message), level ); } virtual void setLogFilename( ::CEGUI::String const & filename, bool append=false ) { if( bp::override func_setLogFilename = this->get_override( "setLogFilename" ) ) func_setLogFilename( boost::ref(filename), append ); else{ this->CEGUI::DefaultLogger::setLogFilename( boost::ref(filename), append ); } } void default_setLogFilename( ::CEGUI::String const & filename, bool append=false ) { CEGUI::DefaultLogger::setLogFilename( boost::ref(filename), append ); } }; void register_DefaultLogger_class(){ { //::CEGUI::DefaultLogger typedef bp::class_< DefaultLogger_wrapper, bp::bases< CEGUI::Logger >, boost::noncopyable > DefaultLogger_exposer_t; DefaultLogger_exposer_t DefaultLogger_exposer = DefaultLogger_exposer_t( "DefaultLogger", "*!\n\ \n\ Default implementation for the Logger class.\n\ If you want to redirect CEGUI logs to some place other than a text file,\n\ implement your own Logger implementation and create a object of the\n\ Logger type before creating the CEGUI.System singleton.\n\ *\n", bp::no_init ); bp::scope DefaultLogger_scope( DefaultLogger_exposer ); DefaultLogger_exposer.def( bp::init< >() ); { //::CEGUI::DefaultLogger::logEvent typedef void ( ::CEGUI::DefaultLogger::*logEvent_function_type )( ::CEGUI::String const &,::CEGUI::LoggingLevel ) ; typedef void ( DefaultLogger_wrapper::*default_logEvent_function_type )( ::CEGUI::String const &,::CEGUI::LoggingLevel ) ; DefaultLogger_exposer.def( "logEvent" , logEvent_function_type(&::CEGUI::DefaultLogger::logEvent) , default_logEvent_function_type(&DefaultLogger_wrapper::default_logEvent) , ( bp::arg("message"), bp::arg("level")=::CEGUI::Standard ) ); } { //::CEGUI::DefaultLogger::setLogFilename typedef void ( ::CEGUI::DefaultLogger::*setLogFilename_function_type )( ::CEGUI::String const &,bool ) ; typedef void ( DefaultLogger_wrapper::*default_setLogFilename_function_type )( ::CEGUI::String const &,bool ) ; DefaultLogger_exposer.def( "setLogFilename" , setLogFilename_function_type(&::CEGUI::DefaultLogger::setLogFilename) , default_setLogFilename_function_type(&DefaultLogger_wrapper::default_setLogFilename) , ( bp::arg("filename"), bp::arg("append")=(bool)(false) ) ); } } }
geminy/aidear
oss/cegui/cegui-0.8.7/cegui/src/ScriptModules/Python/bindings/output/CEGUI/DefaultLogger.pypp.cpp
C++
gpl-3.0
3,612
/* Copyright 2015 the SumatraPDF project authors (see AUTHORS file). License: GPLv3 */ // utils #include "BaseUtil.h" #include "Dpi.h" #include "FileUtil.h" #include "GdiPlusUtil.h" #include "LabelWithCloseWnd.h" #include "UITask.h" #include "WinUtil.h" // rendering engines #include "BaseEngine.h" #include "EngineManager.h" // layout controllers #include "SettingsStructs.h" #include "Controller.h" #include "FileHistory.h" #include "GlobalPrefs.h" // ui #include "SumatraPDF.h" #include "WindowInfo.h" #include "TabInfo.h" #include "resource.h" #include "AppPrefs.h" #include "Favorites.h" #include "Menu.h" #include "SumatraDialogs.h" #include "Tabs.h" #include "Translations.h" Favorite *Favorites::GetByMenuId(int menuId, DisplayState **dsOut) { DisplayState *ds; for (size_t i = 0; (ds = gFileHistory.Get(i)) != nullptr; i++) { for (size_t j = 0; j < ds->favorites->Count(); j++) { if (menuId == ds->favorites->At(j)->menuId) { if (dsOut) *dsOut = ds; return ds->favorites->At(j); } } } return nullptr; } DisplayState *Favorites::GetByFavorite(Favorite *fn) { DisplayState *ds; for (size_t i = 0; (ds = gFileHistory.Get(i)) != nullptr; i++) { if (ds->favorites->Contains(fn)) return ds; } return nullptr; } void Favorites::ResetMenuIds() { DisplayState *ds; for (size_t i = 0; (ds = gFileHistory.Get(i)) != nullptr; i++) { for (size_t j = 0; j < ds->favorites->Count(); j++) { ds->favorites->At(j)->menuId = 0; } } } DisplayState *Favorites::GetFavByFilePath(const WCHAR *filePath) { // it's likely that we'll ask about the info for the same // file as in previous call, so use one element cache DisplayState *ds = gFileHistory.Get(idxCache); if (!ds || !str::Eq(ds->filePath, filePath)) ds = gFileHistory.Find(filePath, &idxCache); return ds; } bool Favorites::IsPageInFavorites(const WCHAR *filePath, int pageNo) { DisplayState *fav = GetFavByFilePath(filePath); if (!fav) return false; for (size_t i = 0; i < fav->favorites->Count(); i++) { if (pageNo == fav->favorites->At(i)->pageNo) return true; } return false; } static Favorite *FindByPage(DisplayState *ds, int pageNo, const WCHAR *pageLabel=nullptr) { if (pageLabel) { for (size_t i = 0; i < ds->favorites->Count(); i++) { if (str::Eq(ds->favorites->At(i)->pageLabel, pageLabel)) return ds->favorites->At(i); } } for (size_t i = 0; i < ds->favorites->Count(); i++) { if (pageNo == ds->favorites->At(i)->pageNo) return ds->favorites->At(i); } return nullptr; } static int SortByPageNo(const void *a, const void *b) { Favorite *na = *(Favorite **)a; Favorite *nb = *(Favorite **)b; // sort lower page numbers first return na->pageNo - nb->pageNo; } void Favorites::AddOrReplace(const WCHAR *filePath, int pageNo, const WCHAR *name, const WCHAR *pageLabel) { DisplayState *fav = GetFavByFilePath(filePath); if (!fav) { CrashIf(gGlobalPrefs->rememberOpenedFiles); fav = NewDisplayState(filePath); gFileHistory.Append(fav); } Favorite *fn = FindByPage(fav, pageNo, pageLabel); if (fn) { str::ReplacePtr(&fn->name, name); CrashIf(fn->pageLabel && !str::Eq(fn->pageLabel, pageLabel)); } else { fn = NewFavorite(pageNo, name, pageLabel); fav->favorites->Append(fn); fav->favorites->Sort(SortByPageNo); } } void Favorites::Remove(const WCHAR *filePath, int pageNo) { DisplayState *fav = GetFavByFilePath(filePath); if (!fav) return; Favorite *fn = FindByPage(fav, pageNo); if (!fn) return; fav->favorites->Remove(fn); DeleteFavorite(fn); if (!gGlobalPrefs->rememberOpenedFiles && 0 == fav->favorites->Count()) { gFileHistory.Remove(fav); DeleteDisplayState(fav); } } void Favorites::RemoveAllForFile(const WCHAR *filePath) { DisplayState *fav = GetFavByFilePath(filePath); if (!fav) return; for (size_t i = 0; i < fav->favorites->Count(); i++) { DeleteFavorite(fav->favorites->At(i)); } fav->favorites->Reset(); if (!gGlobalPrefs->rememberOpenedFiles) { gFileHistory.Remove(fav); DeleteDisplayState(fav); } } // Note: those might be too big #define MAX_FAV_SUBMENUS 10 #define MAX_FAV_MENUS 10 MenuDef menuDefFavContext[] = { { _TRN("Remove from favorites"), IDM_FAV_DEL, 0 } }; static bool HasFavorites() { DisplayState *ds; for (size_t i = 0; (ds = gFileHistory.Get(i)) != nullptr; i++) { if (ds->favorites->Count() > 0) return true; } return false; } // caller has to free() the result static WCHAR *FavReadableName(Favorite *fn) { ScopedMem<WCHAR> plainLabel(str::Format(L"%d", fn->pageNo)); const WCHAR *label = fn->pageLabel ? fn->pageLabel : plainLabel; if (fn->name) { ScopedMem<WCHAR> pageNo(str::Format(_TR("(page %s)"), label)); return str::Join(fn->name, L" ", pageNo); } return str::Format(_TR("Page %s"), label); } // caller has to free() the result static WCHAR *FavCompactReadableName(DisplayState *fav, Favorite *fn, bool isCurrent=false) { ScopedMem<WCHAR> rn(FavReadableName(fn)); if (isCurrent) return str::Format(L"%s : %s", _TR("Current file"), rn.Get()); const WCHAR *fp = path::GetBaseName(fav->filePath); return str::Format(L"%s : %s", fp, rn.Get()); } static void AppendFavMenuItems(HMENU m, DisplayState *f, UINT& idx, bool combined, bool isCurrent) { for (size_t i = 0; i < f->favorites->Count(); i++) { if (i >= MAX_FAV_MENUS) return; Favorite *fn = f->favorites->At(i); fn->menuId = idx++; ScopedMem<WCHAR> s; if (combined) s.Set(FavCompactReadableName(f, fn, isCurrent)); else s.Set(FavReadableName(fn)); AppendMenu(m, MF_STRING, (UINT_PTR)fn->menuId, win::menu::ToSafeString(s, s)); } } static int SortByBaseFileName(const void *a, const void *b) { const WCHAR *filePathA = *(const WCHAR **)a; const WCHAR *filePathB = *(const WCHAR **)b; return str::CmpNatural(path::GetBaseName(filePathA), path::GetBaseName(filePathB)); } static void GetSortedFilePaths(Vec<const WCHAR *>& filePathsSortedOut, DisplayState *toIgnore=nullptr) { DisplayState *ds; for (size_t i = 0; (ds = gFileHistory.Get(i)) != nullptr; i++) { if (ds->favorites->Count() > 0 && ds != toIgnore) filePathsSortedOut.Append(ds->filePath); } filePathsSortedOut.Sort(SortByBaseFileName); } // For easy access, we try to show favorites in the menu, similar to a list of // recently opened files. // The first menu items are for currently opened file (up to MAX_FAV_MENUS), based // on the assumption that user is usually interested in navigating current file. // Then we have a submenu for each file for which there are bookmarks (up to // MAX_FAV_SUBMENUS), each having up to MAX_FAV_MENUS menu items. // If not all favorites can be shown, we also enable "Show all favorites" menu which // will provide a way to see all favorites. // Note: not sure if that's the best layout. Maybe we should always use submenu and // put the submenu for current file as the first one (potentially named as "Current file" // or some such, to make it stand out from other submenus) static void AppendFavMenus(HMENU m, const WCHAR *currFilePath) { // To minimize mouse movement when navigating current file via favorites // menu, put favorites for current file first DisplayState *currFileFav = nullptr; if (currFilePath) { currFileFav = gFavorites.GetFavByFilePath(currFilePath); } // sort the files with favorites by base file name of file path Vec<const WCHAR *> filePathsSorted; if (HasPermission(Perm_DiskAccess)) { // only show favorites for other files, if we're allowed to open them GetSortedFilePaths(filePathsSorted, currFileFav); } if (currFileFav && currFileFav->favorites->Count() > 0) filePathsSorted.InsertAt(0, currFileFav->filePath); if (filePathsSorted.Count() == 0) return; AppendMenu(m, MF_SEPARATOR, 0, nullptr); gFavorites.ResetMenuIds(); UINT menuId = IDM_FAV_FIRST; size_t menusCount = filePathsSorted.Count(); if (menusCount > MAX_FAV_MENUS) menusCount = MAX_FAV_MENUS; for (size_t i = 0; i < menusCount; i++) { const WCHAR *filePath = filePathsSorted.At(i); DisplayState *f = gFavorites.GetFavByFilePath(filePath); CrashIf(!f); HMENU sub = m; bool combined = (f->favorites->Count() == 1); if (!combined) sub = CreateMenu(); AppendFavMenuItems(sub, f, menuId, combined, f == currFileFav); if (!combined) { if (f == currFileFav) { AppendMenu(m, MF_POPUP | MF_STRING, (UINT_PTR)sub, _TR("Current file")); } else { ScopedMem<WCHAR> tmp; const WCHAR *fileName = win::menu::ToSafeString(path::GetBaseName(filePath), tmp); AppendMenu(m, MF_POPUP | MF_STRING, (UINT_PTR)sub, fileName); } } } } // Called when a user opens "Favorites" top-level menu. We need to construct // the menu: // - disable add/remove menu items if no document is opened // - if a document is opened and the page is already bookmarked, // disable "add" menu item and enable "remove" menu item // - if a document is opened and the page is not bookmarked, // enable "add" menu item and disable "remove" menu item void RebuildFavMenu(WindowInfo *win, HMENU menu) { if (!win->IsDocLoaded()) { win::menu::SetEnabled(menu, IDM_FAV_ADD, false); win::menu::SetEnabled(menu, IDM_FAV_DEL, false); AppendFavMenus(menu, nullptr); } else { ScopedMem<WCHAR> label(win->ctrl->GetPageLabel(win->currPageNo)); bool isBookmarked = gFavorites.IsPageInFavorites(win->ctrl->FilePath(), win->currPageNo); if (isBookmarked) { win::menu::SetEnabled(menu, IDM_FAV_ADD, false); ScopedMem<WCHAR> s(str::Format(_TR("Remove page %s from favorites"), label.Get())); win::menu::SetText(menu, IDM_FAV_DEL, s); } else { win::menu::SetEnabled(menu, IDM_FAV_DEL, false); ScopedMem<WCHAR> s(str::Format(_TR("Add page %s to favorites"), label.Get())); win::menu::SetText(menu, IDM_FAV_ADD, s); } AppendFavMenus(menu, win->ctrl->FilePath()); } win::menu::SetEnabled(menu, IDM_FAV_TOGGLE, HasFavorites()); } void ToggleFavorites(WindowInfo *win) { if (gGlobalPrefs->showFavorites) { SetSidebarVisibility(win, win->tocVisible, false); } else { SetSidebarVisibility(win, win->tocVisible, true); SetFocus(win->hwndFavTree); } } static void GoToFavorite(WindowInfo *win, int pageNo) { if (!WindowInfoStillValid(win)) return; if (win->IsDocLoaded() && win->ctrl->ValidPageNo(pageNo)) win->ctrl->GoToPage(pageNo, true); // we might have been invoked by clicking on a tree view // switch focus so that keyboard navigation works, which enables // a fluid experience win->Focus(); } // Going to a bookmark within current file scrolls to a given page. // Going to a bookmark in another file, loads the file and scrolls to a page // (similar to how invoking one of the recently opened files works) static void GoToFavorite(WindowInfo *win, DisplayState *f, Favorite *fn) { assert(f && fn); if (!f || !fn) return; WindowInfo *existingWin = FindWindowInfoByFile(f->filePath, true); if (existingWin) { int pageNo = fn->pageNo; uitask::Post([=] { GoToFavorite(existingWin, pageNo); }); return; } if (!HasPermission(Perm_DiskAccess)) return; // When loading a new document, go directly to selected page instead of // first showing last seen page stored in file history // A hacky solution because I don't want to add even more parameters to // LoadDocument() and LoadDocumentInto() int pageNo = fn->pageNo; DisplayState *ds = gFileHistory.Find(f->filePath); if (ds && !ds->useDefaultState && gGlobalPrefs->rememberStatePerDocument) { ds->pageNo = fn->pageNo; ds->scrollPos = PointI(-1, -1); // don't scroll the page pageNo = -1; } LoadArgs args(f->filePath, win); win = LoadDocument(args); if (win) { uitask::Post([=] { (win, pageNo); }); } } void GoToFavoriteByMenuId(WindowInfo *win, int wmId) { DisplayState *f; Favorite *fn = gFavorites.GetByMenuId(wmId, &f); if (fn) GoToFavorite(win, f, fn); } static void GoToFavForTVItem(WindowInfo* win, HWND hTV, HTREEITEM hItem=nullptr) { if (nullptr == hItem) hItem = TreeView_GetSelection(hTV); TVITEM item; item.hItem = hItem; item.mask = TVIF_PARAM; TreeView_GetItem(hTV, &item); Favorite *fn = (Favorite *)item.lParam; if (!fn) { // can happen for top-level node which is not associated with a favorite // but only serves a parent node for favorites for a given file return; } DisplayState *f = gFavorites.GetByFavorite(fn); GoToFavorite(win, f, fn); } static HTREEITEM InsertFavSecondLevelNode(HWND hwnd, HTREEITEM parent, Favorite *fn) { TV_INSERTSTRUCT tvinsert; tvinsert.hParent = parent; tvinsert.hInsertAfter = TVI_LAST; tvinsert.itemex.mask = TVIF_TEXT | TVIF_STATE | TVIF_PARAM; tvinsert.itemex.state = 0; tvinsert.itemex.stateMask = TVIS_EXPANDED; tvinsert.itemex.lParam = (LPARAM)fn; ScopedMem<WCHAR> s(FavReadableName(fn)); tvinsert.itemex.pszText = s; return TreeView_InsertItem(hwnd, &tvinsert); } static void InsertFavSecondLevelNodes(HWND hwnd, HTREEITEM parent, DisplayState *f) { for (size_t i = 0; i < f->favorites->Count(); i++) { InsertFavSecondLevelNode(hwnd, parent, f->favorites->At(i)); } } static HTREEITEM InsertFavTopLevelNode(HWND hwnd, DisplayState *fav, bool isExpanded) { WCHAR *s = nullptr; bool collapsed = fav->favorites->Count() == 1; if (collapsed) isExpanded = false; TV_INSERTSTRUCT tvinsert; tvinsert.hParent = nullptr; tvinsert.hInsertAfter = TVI_LAST; tvinsert.itemex.mask = TVIF_TEXT | TVIF_STATE | TVIF_PARAM; tvinsert.itemex.state = isExpanded ? TVIS_EXPANDED : 0; tvinsert.itemex.stateMask = TVIS_EXPANDED; tvinsert.itemex.lParam = 0; if (collapsed) { Favorite *fn = fav->favorites->At(0); tvinsert.itemex.lParam = (LPARAM)fn; s = FavCompactReadableName(fav, fn); tvinsert.itemex.pszText = s; } else { tvinsert.itemex.pszText = (WCHAR*)path::GetBaseName(fav->filePath); } HTREEITEM ret = TreeView_InsertItem(hwnd, &tvinsert); free(s); return ret; } void PopulateFavTreeIfNeeded(WindowInfo *win) { HWND hwndTree = win->hwndFavTree; if (TreeView_GetCount(hwndTree) > 0) return; Vec<const WCHAR *> filePathsSorted; GetSortedFilePaths(filePathsSorted); SendMessage(hwndTree, WM_SETREDRAW, FALSE, 0); for (size_t i = 0; i < filePathsSorted.Count(); i++) { DisplayState *f = gFavorites.GetFavByFilePath(filePathsSorted.At(i)); bool isExpanded = win->expandedFavorites.Contains(f); HTREEITEM node = InsertFavTopLevelNode(hwndTree, f, isExpanded); if (f->favorites->Count() > 1) InsertFavSecondLevelNodes(hwndTree, node, f); } SendMessage(hwndTree, WM_SETREDRAW, TRUE, 0); UINT fl = RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN; RedrawWindow(hwndTree, nullptr, nullptr, fl); } void UpdateFavoritesTree(WindowInfo *win) { HWND hwndTree = win->hwndFavTree; if (TreeView_GetCount(hwndTree) > 0) { // PopulateFavTreeIfNeeded will re-enable WM_SETREDRAW SendMessage(hwndTree, WM_SETREDRAW, FALSE, 0); TreeView_DeleteAllItems(hwndTree); PopulateFavTreeIfNeeded(win); } // hide the favorites tree if we've removed the last favorite if (0 == TreeView_GetCount(hwndTree)) { SetSidebarVisibility(win, win->tocVisible, false); } } void UpdateFavoritesTreeForAllWindows() { for (WindowInfo *win : gWindows) { UpdateFavoritesTree(win); } } static DocTocItem *TocItemForPageNo(DocTocItem *item, int pageNo) { DocTocItem *currItem = nullptr; for (; item; item = item->next) { if (1 <= item->pageNo && item->pageNo <= pageNo) currItem = item; if (item->pageNo >= pageNo) break; // find any child item closer to the specified page DocTocItem *subItem = TocItemForPageNo(item->child, pageNo); if (subItem) currItem = subItem; } return currItem; } void AddFavorite(WindowInfo *win) { TabInfo *tab = win->currentTab; CrashIf(!tab); int pageNo = win->currPageNo; ScopedMem<WCHAR> name; if (tab->ctrl->HasTocTree()) { // use the current ToC heading as default name DocTocItem *root = tab->ctrl->GetTocTree(); DocTocItem *item = TocItemForPageNo(root, pageNo); if (item) name.Set(str::Dup(item->title)); delete root; } ScopedMem<WCHAR> pageLabel(tab->ctrl->GetPageLabel(pageNo)); bool shouldAdd = Dialog_AddFavorite(win->hwndFrame, pageLabel, name); if (!shouldAdd) return; ScopedMem<WCHAR> plainLabel(str::Format(L"%d", pageNo)); bool needsLabel = !str::Eq(plainLabel, pageLabel); RememberFavTreeExpansionStateForAllWindows(); gFavorites.AddOrReplace(tab->filePath, pageNo, name, needsLabel ? pageLabel.Get() : nullptr); // expand newly added favorites by default DisplayState *fav = gFavorites.GetFavByFilePath(tab->filePath); if (fav && fav->favorites->Count() == 2) win->expandedFavorites.Append(fav); UpdateFavoritesTreeForAllWindows(); prefs::Save(); } void DelFavorite(WindowInfo *win) { CrashIf(!win->currentTab); RememberFavTreeExpansionStateForAllWindows(); gFavorites.Remove(win->currentTab->filePath, win->currPageNo); UpdateFavoritesTreeForAllWindows(); prefs::Save(); } void RememberFavTreeExpansionState(WindowInfo *win) { win->expandedFavorites.Reset(); HTREEITEM treeItem = TreeView_GetRoot(win->hwndFavTree); while (treeItem) { TVITEM item; item.hItem = treeItem; item.mask = TVIF_PARAM | TVIF_STATE; item.stateMask = TVIS_EXPANDED; TreeView_GetItem(win->hwndFavTree, &item); if ((item.state & TVIS_EXPANDED) != 0) { item.hItem = TreeView_GetChild(win->hwndFavTree, treeItem); item.mask = TVIF_PARAM; TreeView_GetItem(win->hwndFavTree, &item); Favorite *fn = (Favorite *)item.lParam; DisplayState *f = gFavorites.GetByFavorite(fn); win->expandedFavorites.Append(f); } treeItem = TreeView_GetNextSibling(win->hwndFavTree, treeItem); } } void RememberFavTreeExpansionStateForAllWindows() { for (size_t i = 0; i < gWindows.Count(); i++) { RememberFavTreeExpansionState(gWindows.At(i)); } } static LRESULT OnFavTreeNotify(WindowInfo *win, LPNMTREEVIEW pnmtv) { switch (pnmtv->hdr.code) { // TVN_SELCHANGED intentionally not implemented (mouse clicks are handled // in NM_CLICK, and keyboard navigation in NM_RETURN and TVN_KEYDOWN) case TVN_KEYDOWN: { TV_KEYDOWN *ptvkd = (TV_KEYDOWN *)pnmtv; if (VK_TAB == ptvkd->wVKey) { if (win->tabsVisible && IsCtrlPressed()) TabsOnCtrlTab(win, IsShiftPressed()); else AdvanceFocus(win); return 1; } break; } case NM_CLICK: { // Determine which item has been clicked (if any) TVHITTESTINFO ht = { 0 }; DWORD pos = GetMessagePos(); ht.pt.x = GET_X_LPARAM(pos); ht.pt.y = GET_Y_LPARAM(pos); MapWindowPoints(HWND_DESKTOP, pnmtv->hdr.hwndFrom, &ht.pt, 1); TreeView_HitTest(pnmtv->hdr.hwndFrom, &ht); if ((ht.flags & TVHT_ONITEM)) GoToFavForTVItem(win, pnmtv->hdr.hwndFrom, ht.hItem); break; } case NM_RETURN: GoToFavForTVItem(win, pnmtv->hdr.hwndFrom); break; case NM_CUSTOMDRAW: return CDRF_DODEFAULT; } return -1; } static void OnFavTreeContextMenu(WindowInfo *win, PointI pt) { TVITEM item; if (pt.x != -1 || pt.y != -1) { TVHITTESTINFO ht = { 0 }; ht.pt.x = pt.x; ht.pt.y = pt.y; MapWindowPoints(HWND_DESKTOP, win->hwndFavTree, &ht.pt, 1); TreeView_HitTest(win->hwndFavTree, &ht); if ((ht.flags & TVHT_ONITEM) == 0) return; // only display menu if over a node in tree TreeView_SelectItem(win->hwndFavTree, ht.hItem); item.hItem = ht.hItem; } else { item.hItem = TreeView_GetSelection(win->hwndFavTree); if (!item.hItem) return; RECT rcItem; if (TreeView_GetItemRect(win->hwndFavTree, item.hItem, &rcItem, TRUE)) { MapWindowPoints(win->hwndFavTree, HWND_DESKTOP, (POINT *)&rcItem, 2); pt.x = rcItem.left; pt.y = rcItem.bottom; } else { WindowRect rc(win->hwndFavTree); pt = rc.TL(); } } item.mask = TVIF_PARAM; TreeView_GetItem(win->hwndFavTree, &item); Favorite *toDelete = (Favorite *)item.lParam; HMENU popup = BuildMenuFromMenuDef(menuDefFavContext, dimof(menuDefFavContext), CreatePopupMenu()); INT cmd = TrackPopupMenu(popup, TPM_RETURNCMD | TPM_RIGHTBUTTON, pt.x, pt.y, 0, win->hwndFavTree, nullptr); DestroyMenu(popup); if (IDM_FAV_DEL == cmd) { RememberFavTreeExpansionStateForAllWindows(); if (toDelete) { DisplayState *f = gFavorites.GetByFavorite(toDelete); gFavorites.Remove(f->filePath, toDelete->pageNo); } else { // toDelete == nullptr => this is a parent node signifying all bookmarks in a file item.hItem = TreeView_GetChild(win->hwndFavTree, item.hItem); item.mask = TVIF_PARAM; TreeView_GetItem(win->hwndFavTree, &item); toDelete = (Favorite *)item.lParam; DisplayState *f = gFavorites.GetByFavorite(toDelete); gFavorites.RemoveAllForFile(f->filePath); } UpdateFavoritesTreeForAllWindows(); prefs::Save(); // TODO: it would be nice to have a system for undo-ing things, like in Gmail, // so that we can do destructive operations without asking for permission via // invasive model dialog boxes but also allow reverting them if were done // by mistake } } static WNDPROC DefWndProcFavTree = nullptr; static LRESULT CALLBACK WndProcFavTree(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { WindowInfo *win = FindWindowInfoByHwnd(hwnd); if (!win) return CallWindowProc(DefWndProcFavTree, hwnd, msg, wParam, lParam); switch (msg) { case WM_ERASEBKGND: return FALSE; case WM_CHAR: if (VK_ESCAPE == wParam && gGlobalPrefs->escToExit && MayCloseWindow(win)) CloseWindow(win, true); break; case WM_MOUSEWHEEL: case WM_MOUSEHWHEEL: // scroll the canvas if the cursor isn't over the ToC tree if (!IsCursorOverWindow(win->hwndFavTree)) return SendMessage(win->hwndCanvas, msg, wParam, lParam); break; } return CallWindowProc(DefWndProcFavTree, hwnd, msg, wParam, lParam); } static WNDPROC DefWndProcFavBox = nullptr; static LRESULT CALLBACK WndProcFavBox(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { WindowInfo *win = FindWindowInfoByHwnd(hwnd); if (!win) return CallWindowProc(DefWndProcFavBox, hwnd, message, wParam, lParam); switch (message) { case WM_SIZE: LayoutTreeContainer(win->favLabelWithClose, win->hwndFavTree); break; case WM_COMMAND: if (LOWORD(wParam) == IDC_FAV_LABEL_WITH_CLOSE) ToggleFavorites(win); break; case WM_NOTIFY: if (LOWORD(wParam) == IDC_FAV_TREE) { LPNMTREEVIEW pnmtv = (LPNMTREEVIEW) lParam; LRESULT res = OnFavTreeNotify(win, pnmtv); if (res != -1) return res; } break; case WM_CONTEXTMENU: if (win->hwndFavTree == (HWND)wParam) { OnFavTreeContextMenu(win, PointI(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); return 0; } break; } return CallWindowProc(DefWndProcFavBox, hwnd, message, wParam, lParam); } void CreateFavorites(WindowInfo *win) { win->hwndFavBox = CreateWindow(WC_STATIC, L"", WS_CHILD|WS_CLIPCHILDREN, 0, 0, gGlobalPrefs->sidebarDx, 0, win->hwndFrame, (HMENU)0, GetModuleHandle(nullptr), nullptr); LabelWithCloseWnd *l = CreateLabelWithCloseWnd(win->hwndFavBox, IDC_FAV_LABEL_WITH_CLOSE); win->favLabelWithClose = l; SetPaddingXY(l, 2, 2); SetFont(l, GetDefaultGuiFont()); // label is set in UpdateToolbarSidebarText() win->hwndFavTree = CreateWindowEx(WS_EX_STATICEDGE, WC_TREEVIEW, L"Fav", TVS_HASBUTTONS|TVS_HASLINES|TVS_LINESATROOT|TVS_SHOWSELALWAYS| TVS_TRACKSELECT|TVS_DISABLEDRAGDROP|TVS_NOHSCROLL|TVS_INFOTIP| WS_TABSTOP|WS_VISIBLE|WS_CHILD, 0, 0, 0, 0, win->hwndFavBox, (HMENU)IDC_FAV_TREE, GetModuleHandle(nullptr), nullptr); TreeView_SetUnicodeFormat(win->hwndFavTree, true); if (nullptr == DefWndProcFavTree) DefWndProcFavTree = (WNDPROC)GetWindowLongPtr(win->hwndFavTree, GWLP_WNDPROC); SetWindowLongPtr(win->hwndFavTree, GWLP_WNDPROC, (LONG_PTR)WndProcFavTree); if (nullptr == DefWndProcFavBox) DefWndProcFavBox = (WNDPROC)GetWindowLongPtr(win->hwndFavBox, GWLP_WNDPROC); SetWindowLongPtr(win->hwndFavBox, GWLP_WNDPROC, (LONG_PTR)WndProcFavBox); }
the7day/sumatrapdf
src/Favorites.cpp
C++
gpl-3.0
27,609
package com.puppycrawl.tools.checkstyle.checks.indentation.indentation; //indent:0 exp:0 /** //indent:0 exp:0 * This test-input is intended to be checked using following configuration: //indent:1 exp:1 * //indent:1 exp:1 * arrayInitIndent = 4 //indent:1 exp:1 * basicOffset = 4 //indent:1 exp:1 * braceAdjustment = 0 //indent:1 exp:1 * caseIndent = 4 //indent:1 exp:1 * forceStrictCondition = false //indent:1 exp:1 * lineWrappingIndentation = 4 //indent:1 exp:1 * tabWidth = 4 //indent:1 exp:1 * throwsIndent = 4 //indent:1 exp:1 * //indent:1 exp:1 * @author jrichard //indent:1 exp:1 */ //indent:1 exp:1 public class InputIndentationInvalidWhileIndent { //indent:0 exp:0 /** Creates a new instance of InputIndentationValidWhileIndent */ //indent:4 exp:4 public InputIndentationInvalidWhileIndent() { //indent:4 exp:4 } //indent:4 exp:4 private void method1() //indent:4 exp:4 { //indent:4 exp:4 boolean test = true; //indent:8 exp:8 while (test) { //indent:9 exp:8 warn } //indent:7 exp:8 warn while (test) //indent:7 exp:8 warn { //indent:9 exp:8 warn } //indent:9 exp:8 warn while (test) //indent:9 exp:8 warn { //indent:6 exp:8 warn System.getProperty("foo"); //indent:14 exp:12 warn } //indent:6 exp:8 warn while (test) { //indent:10 exp:8 warn System.getProperty("foo"); //indent:12 exp:12 } //indent:10 exp:8 warn while (test) { //indent:10 exp:8 warn System.getProperty("foo"); //indent:12 exp:12 System.getProperty("foo"); //indent:12 exp:12 } //indent:10 exp:8 warn while (test) //indent:6 exp:8 warn { //indent:10 exp:8 warn System.getProperty("foo"); //indent:12 exp:12 System.getProperty("foo"); //indent:12 exp:12 } //indent:6 exp:8 warn while (test) { // : this is allowed //indent:8 exp:8 if (test) { //indent:14 exp:12 warn System.getProperty("foo"); //indent:18 exp:16 warn } //indent:14 exp:12 warn System.getProperty("foo"); //indent:14 exp:12 warn } //indent:10 exp:8 warn while (test //indent:8 exp:8 && 4 < 7 && 8 < 9 //indent:10 exp:12 warn && 3 < 4) { //indent:12 exp:>=12 } //indent:8 exp:8 while (test //indent:8 exp:8 && 4 < 7 && 8 < 9 //indent:12 exp:>=12 && 3 < 4) { //indent:10 exp:12 warn } //indent:8 exp:8 while (test //indent:8 exp:8 && 4 < 7 && 8 < 9 //indent:12 exp:>=12 && 3 < 4) //indent:10 exp:12 warn { //indent:8 exp:8 } //indent:8 exp:8 while (test //indent:8 exp:8 && 4 < 7 && 8 < 9 //indent:12 exp:>=12 && 3 < 4 //indent:12 exp:>=12 ) { //indent:5 exp:8 warn } //indent:8 exp:8 while (test //indent:8 exp:8 && 4 < 7 && 8 < 9 //indent:12 exp:>=12 && 3 < 4 //indent:12 exp:>=12 ) { //indent:10 exp:8 warn } //indent:8 exp:8 while (test //indent:8 exp:8 && 4 < 7 && 8 < 9 //indent:12 exp:>=12 && 3 < 4 //indent:12 exp:>=12 ) //indent:10 exp:8 warn { //indent:8 exp:8 } //indent:8 exp:8 while (true) //indent:8 exp:8 { //indent:8 exp:8 continue; //indent:8 exp:12 warn } //indent:8 exp:8 } //indent:4 exp:4 } //indent:0 exp:0
jochenvdv/checkstyle
src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationInvalidWhileIndent.java
Java
lgpl-2.1
4,344
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.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. */ package com.linkedin.pinot.routing.builder; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.helix.model.InstanceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linkedin.pinot.common.utils.CommonConstants; public class RoutingTableInstancePruner { private static final Logger LOGGER = LoggerFactory.getLogger(RoutingTableInstancePruner.class); private Map<String, InstanceConfig> instanceConfigMap; public RoutingTableInstancePruner(List<InstanceConfig> instanceConfigList) { instanceConfigMap = new HashMap<String, InstanceConfig>(); for (InstanceConfig config : instanceConfigList) { instanceConfigMap.put(config.getInstanceName(), config); } } public boolean isShuttingDown(String instanceName) { if (!instanceConfigMap.containsKey(instanceName)) { return false; } boolean status = false; if (instanceConfigMap.get(instanceName).getRecord().getSimpleField(CommonConstants.Helix.IS_SHUTDOWN_IN_PROGRESS) != null) { try { if (instanceConfigMap.get(instanceName).getRecord() == null) { return false; } if (instanceConfigMap.get(instanceName).getRecord() .getSimpleField(CommonConstants.Helix.IS_SHUTDOWN_IN_PROGRESS) != null) { status = Boolean.valueOf(instanceConfigMap.get(instanceName).getRecord() .getSimpleField(CommonConstants.Helix.IS_SHUTDOWN_IN_PROGRESS)); if (status == true) { LOGGER.info("found an instance : {} in shutting down state", instanceName); } } } catch (Exception e) { LOGGER.error("unknown value found while parsing boolean isShuttingDownField ", e); } } return status; } }
izzizz/pinot
pinot-transport/src/main/java/com/linkedin/pinot/routing/builder/RoutingTableInstancePruner.java
Java
apache-2.0
2,428
import dataclasses from typing import ClassVar, Dict, List, Set, Tuple, Type from collections import OrderedDict @dataclasses.dataclass class A: a: List[int] = <error descr="Mutable default '[]' is not allowed. Use 'default_factory'">[]</error> b: List[int] = <error descr="Mutable default 'list()' is not allowed. Use 'default_factory'">list()</error> c: Set[int] = <error descr="Mutable default '{1}' is not allowed. Use 'default_factory'">{1}</error> d: Set[int] = <error descr="Mutable default 'set()' is not allowed. Use 'default_factory'">set()</error> e: Tuple[int, ...] = () f: Tuple[int, ...] = tuple() g: ClassVar[List[int]] = [] h: ClassVar = [] i: Dict[int, int] = <error descr="Mutable default '{1: 2}' is not allowed. Use 'default_factory'">{1: 2}</error> j: Dict[int, int] = <error descr="Mutable default 'dict()' is not allowed. Use 'default_factory'">dict()</error> k = [] l = list() m: Dict[int, int] = <error descr="Mutable default 'OrderedDict()' is not allowed. Use 'default_factory'">OrderedDict()</error> n: FrozenSet[int] = frozenset() a2: Type[List[int]] = list b2: Type[Set[int]] = set c2: Type[Tuple[int, ...]] = tuple
siosio/intellij-community
python/testData/inspections/PyDataclassInspection/defaultFieldValue.py
Python
apache-2.0
1,215
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.textstructure.structurefinder; import org.elasticsearch.core.Tuple; import org.elasticsearch.xpack.textstructure.structurefinder.GrokPatternCreator.ValueOnlyGrokPatternCandidate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.containsInAnyOrder; public class GrokPatternCreatorTests extends TextStructureTestCase { public void testBuildFieldName() { Map<String, Integer> fieldNameCountStore = new HashMap<>(); assertEquals("field", GrokPatternCreator.buildFieldName(fieldNameCountStore, "field")); assertEquals("field2", GrokPatternCreator.buildFieldName(fieldNameCountStore, "field")); assertEquals("field3", GrokPatternCreator.buildFieldName(fieldNameCountStore, "field")); assertEquals("extra_timestamp", GrokPatternCreator.buildFieldName(fieldNameCountStore, "extra_timestamp")); assertEquals("field4", GrokPatternCreator.buildFieldName(fieldNameCountStore, "field")); assertEquals("uri", GrokPatternCreator.buildFieldName(fieldNameCountStore, "uri")); assertEquals("extra_timestamp2", GrokPatternCreator.buildFieldName(fieldNameCountStore, "extra_timestamp")); assertEquals("field5", GrokPatternCreator.buildFieldName(fieldNameCountStore, "field")); } public void testPopulatePrefacesAndEpiloguesGivenTimestamp() { Collection<String> matchingStrings = Arrays.asList( "[2018-01-25T15:33:23] DEBUG ", "[2018-01-24T12:33:23] ERROR ", "junk [2018-01-22T07:33:23] INFO ", "[2018-01-21T03:33:23] DEBUG " ); ValueOnlyGrokPatternCandidate candidate = new ValueOnlyGrokPatternCandidate("TIMESTAMP_ISO8601", "date", "extra_timestamp"); Map<String, Integer> fieldNameCountStore = new HashMap<>(); Collection<String> prefaces = new ArrayList<>(); Collection<String> epilogues = new ArrayList<>(); candidate.processCaptures(explanation, fieldNameCountStore, matchingStrings, prefaces, epilogues, null, null, NOOP_TIMEOUT_CHECKER); assertThat(prefaces, containsInAnyOrder("[", "[", "junk [", "[")); assertThat(epilogues, containsInAnyOrder("] DEBUG ", "] ERROR ", "] INFO ", "] DEBUG ")); } public void testPopulatePrefacesAndEpiloguesGivenEmailAddress() { Collection<String> matchingStrings = Arrays.asList("before alice@acme.com after", "abc bob@acme.com xyz", "carol@acme.com"); ValueOnlyGrokPatternCandidate candidate = new ValueOnlyGrokPatternCandidate("EMAILADDRESS", "keyword", "email"); Map<String, Integer> fieldNameCountStore = new HashMap<>(); Collection<String> prefaces = new ArrayList<>(); Collection<String> epilogues = new ArrayList<>(); candidate.processCaptures(explanation, fieldNameCountStore, matchingStrings, prefaces, epilogues, null, null, NOOP_TIMEOUT_CHECKER); assertThat(prefaces, containsInAnyOrder("before ", "abc ", "")); assertThat(epilogues, containsInAnyOrder(" after", " xyz", "")); } public void testAppendBestGrokMatchForStringsGivenTimestampsAndLogLevels() { Collection<String> snippets = Arrays.asList( "[2018-01-25T15:33:23] DEBUG ", "[2018-01-24T12:33:23] ERROR ", "junk [2018-01-22T07:33:23] INFO ", "[2018-01-21T03:33:23] DEBUG " ); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); assertEquals( ".*?\\[%{TIMESTAMP_ISO8601:extra_timestamp}\\] %{LOGLEVEL:loglevel} ", grokPatternCreator.getOverallGrokPatternBuilder().toString() ); } public void testAppendBestGrokMatchForStringsGivenNumbersInBrackets() { Collection<String> snippets = Arrays.asList("(-2)", " (-3)", " (4)", " (-5) "); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); assertEquals(".*?\\(%{INT:field}\\).*?", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testAppendBestGrokMatchForStringsGivenNegativeNumbersWithoutBreak() { Collection<String> snippets = Arrays.asList("before-2 ", "prior to-3", "-4"); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); // It seems sensible that we don't detect these suffices as either base 10 or base 16 numbers assertEquals(".*?", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testAppendBestGrokMatchForStringsGivenHexNumbers() { Collection<String> snippets = Arrays.asList(" abc", " 123", " -123", "1f is hex"); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); assertEquals(".*?%{BASE16NUM:field}.*?", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testAppendBestGrokMatchForStringsGivenHostnamesWithNumbers() { Collection<String> snippets = Arrays.asList("<host1.1.p2ps:", "<host2.1.p2ps:"); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); // We don't want the .1. in the middle to get detected as a hex number assertEquals("<.*?:", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testAppendBestGrokMatchForStringsGivenEmailAddresses() { Collection<String> snippets = Arrays.asList("before alice@acme.com after", "abc bob@acme.com xyz", "carol@acme.com"); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); assertEquals(".*?%{EMAILADDRESS:email}.*?", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testAppendBestGrokMatchForStringsGivenUris() { Collection<String> snippets = Arrays.asList( "main site https://www.elastic.co/ with trailing slash", "https://www.elastic.co/guide/en/x-pack/current/ml-configuring-categories.html#ml-configuring-categories is a section", "download today from https://www.elastic.co/downloads" ); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); assertEquals(".*?%{URI:uri}.*?", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testAppendBestGrokMatchForStringsGivenPaths() { Collection<String> snippets = Arrays.asList("on Mac /Users/dave", "on Windows C:\\Users\\dave", "on Linux /home/dave"); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); assertEquals(".*? .*? %{PATH:path}", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testAppendBestGrokMatchForStringsGivenKvPairs() { Collection<String> snippets = Arrays.asList( "foo=1 and bar=a", "something foo=2 bar=b something else", "foo=3 bar=c", " foo=1 bar=a " ); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.appendBestGrokMatchForStrings(false, snippets, false, 0); assertEquals(".*?\\bfoo=%{USER:foo} .*?\\bbar=%{USER:bar}.*?", grokPatternCreator.getOverallGrokPatternBuilder().toString()); } public void testCreateGrokPatternFromExamplesGivenNamedLogs() { Collection<String> sampleMessages = Arrays.asList( "Sep 8 11:55:06 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'elastic.slack.com/A/IN': 95.110.64.205#53", "Sep 8 11:55:08 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'slack-imgs.com/A/IN': 95.110.64.205#53", "Sep 8 11:55:35 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'www.elastic.co/A/IN': 95.110.68.206#53", "Sep 8 11:55:42 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'b.akamaiedge.net/A/IN': 95.110.64.205#53" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); assertEquals( "%{SYSLOGTIMESTAMP:timestamp} .*? .*?\\[%{INT:field}\\]: %{LOGLEVEL:loglevel} \\(.*? .*? .*?\\) .*? " + "%{QUOTEDSTRING:field2}: %{IP:ipaddress}#%{INT:field3}", grokPatternCreator.createGrokPatternFromExamples("SYSLOGTIMESTAMP", TextStructureUtils.DATE_MAPPING_WITHOUT_FORMAT, "timestamp") ); assertEquals(5, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("loglevel")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("field2")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("ipaddress")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field3")); } public void testCreateGrokPatternFromExamplesGivenCatalinaLogs() { Collection<String> sampleMessages = Arrays.asList( "Aug 29, 2009 12:03:33 AM org.apache.tomcat.util.http.Parameters processParameters\nWARNING: Parameters: " + "Invalid chunk ignored.", "Aug 29, 2009 12:03:40 AM org.apache.tomcat.util.http.Parameters processParameters\nWARNING: Parameters: " + "Invalid chunk ignored.", "Aug 29, 2009 12:03:45 AM org.apache.tomcat.util.http.Parameters processParameters\nWARNING: Parameters: " + "Invalid chunk ignored.", "Aug 29, 2009 12:03:57 AM org.apache.tomcat.util.http.Parameters processParameters\nWARNING: Parameters: " + "Invalid chunk ignored." ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); assertEquals( "%{CATALINA_DATESTAMP:timestamp} .*? .*?\\n%{LOGLEVEL:loglevel}: .*", grokPatternCreator.createGrokPatternFromExamples( "CATALINA_DATESTAMP", TextStructureUtils.DATE_MAPPING_WITHOUT_FORMAT, "timestamp" ) ); assertEquals(1, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("loglevel")); } public void testCreateGrokPatternFromExamplesGivenMultiTimestampLogs() { // Two timestamps: one local, one UTC Collection<String> sampleMessages = Arrays.asList( "559550912540598297\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t38545844\tserv02nw07\t192.168.114.28\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986880\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t9049724\tserv02nw03\t10.120.48.147\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986887\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t884343\tserv02tw03\t192.168.121.189\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912603512850\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t8907014\tserv02nw01\t192.168.118.208\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); assertEquals( "%{INT:field}\\t%{TIMESTAMP_ISO8601:timestamp}\\t%{TIMESTAMP_ISO8601:extra_timestamp}\\t%{INT:field2}\\t.*?\\t" + "%{IP:ipaddress}\\t.*?\\t%{LOGLEVEL:loglevel}\\t.*", grokPatternCreator.createGrokPatternFromExamples( "TIMESTAMP_ISO8601", TextStructureUtils.DATE_MAPPING_WITHOUT_FORMAT, "timestamp" ) ); assertEquals(5, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field")); Map<String, String> expectedDateMapping = new HashMap<>(); expectedDateMapping.put(TextStructureUtils.MAPPING_TYPE_SETTING, "date"); expectedDateMapping.put(TextStructureUtils.MAPPING_FORMAT_SETTING, "iso8601"); assertEquals(expectedDateMapping, mappings.get("extra_timestamp")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field2")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("ipaddress")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("loglevel")); } public void testCreateGrokPatternFromExamplesGivenMultiTimestampLogsAndIndeterminateFormat() { // Two timestamps: one ISO8601, one indeterminate day/month Collection<String> sampleMessages = Arrays.asList( "559550912540598297\t2016-04-20T14:06:53\t20/04/2016 21:06:53,123456\t38545844\tserv02nw07\t192.168.114.28\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986880\t2016-04-20T14:06:53\t20/04/2016 21:06:53,123456\t9049724\tserv02nw03\t10.120.48.147\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986887\t2016-04-20T14:06:53\t20/04/2016 21:06:53,123456\t884343\tserv02tw03\t192.168.121.189\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912603512850\t2016-04-20T14:06:53\t20/04/2016 21:06:53,123456\t8907014\tserv02nw01\t192.168.118.208\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); assertEquals( "%{INT:field}\\t%{TIMESTAMP_ISO8601:timestamp}\\t%{DATESTAMP:extra_timestamp}\\t%{INT:field2}\\t.*?\\t" + "%{IP:ipaddress}\\t.*?\\t%{LOGLEVEL:loglevel}\\t.*", grokPatternCreator.createGrokPatternFromExamples( "TIMESTAMP_ISO8601", TextStructureUtils.DATE_MAPPING_WITHOUT_FORMAT, "timestamp" ) ); assertEquals(5, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field")); Map<String, String> expectedDateMapping = new HashMap<>(); expectedDateMapping.put(TextStructureUtils.MAPPING_TYPE_SETTING, "date_nanos"); expectedDateMapping.put(TextStructureUtils.MAPPING_FORMAT_SETTING, "dd/MM/yyyy HH:mm:ss,SSSSSS"); assertEquals(expectedDateMapping, mappings.get("extra_timestamp")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field2")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("ipaddress")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("loglevel")); } public void testCreateGrokPatternFromExamplesGivenMultiTimestampLogsAndCustomDefinition() { // Two timestamps: one custom, one built-in Collection<String> sampleMessages = Arrays.asList( "559550912540598297\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t38545844\tserv02nw07\t192.168.114.28\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986880\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t9049724\tserv02nw03\t10.120.48.147\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986887\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t884343\tserv02tw03\t192.168.121.189\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912603512850\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t8907014\tserv02nw01\t192.168.118.208\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.singletonMap("CUSTOM_TIMESTAMP", "%{MONTHNUM}/%{MONTHDAY}/%{YEAR} %{HOUR}:%{MINUTE}(?:AM|PM)"), NOOP_TIMEOUT_CHECKER ); Map<String, String> customMapping = new HashMap<>(); customMapping.put(TextStructureUtils.MAPPING_TYPE_SETTING, "date"); customMapping.put(TextStructureUtils.MAPPING_FORMAT_SETTING, "M/dd/yyyy h:mma"); assertEquals( "%{INT:field}\\t%{CUSTOM_TIMESTAMP:timestamp}\\t%{TIMESTAMP_ISO8601:extra_timestamp}\\t%{INT:field2}\\t.*?\\t" + "%{IP:ipaddress}\\t.*?\\t%{LOGLEVEL:loglevel}\\t.*", grokPatternCreator.createGrokPatternFromExamples("CUSTOM_TIMESTAMP", customMapping, "timestamp") ); assertEquals(5, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field")); Map<String, String> expectedDateMapping = new HashMap<>(); expectedDateMapping.put(TextStructureUtils.MAPPING_TYPE_SETTING, "date"); expectedDateMapping.put(TextStructureUtils.MAPPING_FORMAT_SETTING, "iso8601"); assertEquals(expectedDateMapping, mappings.get("extra_timestamp")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field2")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("ipaddress")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("loglevel")); } public void testCreateGrokPatternFromExamplesGivenTimestampAndTimeWithoutDate() { // Two timestamps: one with date, one without Collection<String> sampleMessages = Arrays.asList( "559550912540598297\t2016-04-20T14:06:53\t21:06:53.123456\t38545844\tserv02nw07\t192.168.114.28\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986880\t2016-04-20T14:06:53\t21:06:53.123456\t9049724\tserv02nw03\t10.120.48.147\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986887\t2016-04-20T14:06:53\t21:06:53.123456\t884343\tserv02tw03\t192.168.121.189\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912603512850\t2016-04-20T14:06:53\t21:06:53.123456\t8907014\tserv02nw01\t192.168.118.208\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); assertEquals( "%{INT:field}\\t%{TIMESTAMP_ISO8601:timestamp}\\t%{TIME:time}\\t%{INT:field2}\\t.*?\\t" + "%{IP:ipaddress}\\t.*?\\t%{LOGLEVEL:loglevel}\\t.*", grokPatternCreator.createGrokPatternFromExamples( "TIMESTAMP_ISO8601", TextStructureUtils.DATE_MAPPING_WITHOUT_FORMAT, "timestamp" ) ); assertEquals(5, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("time")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("field2")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("ipaddress")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("loglevel")); } public void testFindFullLineGrokPatternGivenApacheCombinedLogs() { Collection<String> sampleMessages = Arrays.asList( "83.149.9.216 - - [19/Jan/2016:08:13:42 +0000] " + "\"GET /presentations/logstash-monitorama-2013/images/kibana-search.png HTTP/1.1\" 200 203023 " + "\"http://semicomplete.com/presentations/logstash-monitorama-2013/\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36\"", "83.149.9.216 - - [19/Jan/2016:08:13:44 +0000] " + "\"GET /presentations/logstash-monitorama-2013/plugin/zoom-js/zoom.js HTTP/1.1\" 200 7697 " + "\"http://semicomplete.com/presentations/logstash-monitorama-2013/\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36\"", "83.149.9.216 - - [19/Jan/2016:08:13:44 +0000] " + "\"GET /presentations/logstash-monitorama-2013/plugin/highlight/highlight.js HTTP/1.1\" 200 26185 " + "\"http://semicomplete.com/presentations/logstash-monitorama-2013/\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36\"", "83.149.9.216 - - [19/Jan/2016:08:13:42 +0000] " + "\"GET /presentations/logstash-monitorama-2013/images/sad-medic.png HTTP/1.1\" 200 430406 " + "\"http://semicomplete.com/presentations/logstash-monitorama-2013/\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36\"" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); assertEquals( new Tuple<>("timestamp", "%{COMBINEDAPACHELOG}"), grokPatternCreator.findFullLineGrokPattern(randomBoolean() ? "timestamp" : null) ); assertEquals(10, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "text"), mappings.get("agent")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("auth")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("bytes")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("clientip")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "double"), mappings.get("httpversion")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("ident")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("referrer")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("request")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("response")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("verb")); } public void testAdjustForPunctuationGivenCommonPrefix() { Collection<String> snippets = """ ","lab6.localhost","Route Domain","/Common/0","No-lookup","192.168.33.212","No-lookup","192.168.33.132","80","46721",\ "/Common/Subnet_33","TCP","0","","","","","","","","Staged","/Common/policy1","rule1","Accept","","","",\ "0000000000000000" ","lab6.localhost","Route Domain","/Common/0","No-lookup","192.168.143.244","No-lookup","192.168.33.106","55025","162",\ "/Common/Subnet_33","UDP","0","","","","","","","","Staged","/Common/policy1","rule1","Accept","","","",\ "0000000000000000" ","lab6.localhost","Route Domain","/Common/0","No-lookup","192.168.33.3","No-lookup","224.0.0.102","3222","3222",\ "/Common/Subnet_33","UDP","0","","","","","","","","Staged","/Common/policy1","rule1","Accept","","","",\ "0000000000000000"\ """.lines().toList(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); Collection<String> adjustedSnippets = grokPatternCreator.adjustForPunctuation(snippets); assertEquals("\",", grokPatternCreator.getOverallGrokPatternBuilder().toString()); assertNotNull(adjustedSnippets); assertThat( new ArrayList<>(adjustedSnippets), containsInAnyOrder(snippets.stream().map(snippet -> snippet.substring(2)).toArray(String[]::new)) ); } public void testAdjustForPunctuationGivenNoCommonPrefix() { Collection<String> snippets = Arrays.asList( "|client (id:2) was removed from servergroup 'Normal'(id:7) by client 'User1'(id:2)", "|servergroup 'GAME'(id:9) was added by 'User1'(id:2)", "|permission 'i_group_auto_update_type'(id:146) with values (value:30, negated:0, skipchannel:0) " + "was added by 'User1'(id:2) to servergroup 'GAME'(id:9)" ); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, snippets, null, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); Collection<String> adjustedSnippets = grokPatternCreator.adjustForPunctuation(snippets); assertEquals("", grokPatternCreator.getOverallGrokPatternBuilder().toString()); assertSame(snippets, adjustedSnippets); } public void testValidateFullLineGrokPatternGivenValid() { String timestampField = "utc_timestamp"; String grokPattern = "%{INT:serial_no}\\t%{TIMESTAMP_ISO8601:local_timestamp}\\t%{TIMESTAMP_ISO8601:utc_timestamp}\\t" + "%{INT:user_id}\\t%{HOSTNAME:host}\\t%{IP:client_ip}\\t%{WORD:method}\\t%{LOGLEVEL:severity}\\t%{PROG:program}\\t" + "%{GREEDYDATA:message}"; // Two timestamps: one local, one UTC Collection<String> sampleMessages = Arrays.asList( "559550912540598297\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t38545844\tserv02nw07\t192.168.114.28\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986880\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t9049724\tserv02nw03\t10.120.48.147\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986887\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t884343\tserv02tw03\t192.168.121.189\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912603512850\t2016-04-20T14:06:53\t2016-04-20T21:06:53Z\t8907014\tserv02nw01\t192.168.118.208\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.validateFullLineGrokPattern(grokPattern, timestampField); assertEquals(9, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("serial_no")); Map<String, String> expectedDateMapping = new HashMap<>(); expectedDateMapping.put(TextStructureUtils.MAPPING_TYPE_SETTING, "date"); expectedDateMapping.put(TextStructureUtils.MAPPING_FORMAT_SETTING, "iso8601"); assertEquals(expectedDateMapping, mappings.get("local_timestamp")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("user_id")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("host")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("client_ip")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("method")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("severity")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("program")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("message")); } public void testValidateFullLineGrokPatternGivenValidAndCustomDefinition() { String timestampField = "local_timestamp"; String grokPattern = "%{INT:serial_no}\\t%{CUSTOM_TIMESTAMP:local_timestamp}\\t%{TIMESTAMP_ISO8601:utc_timestamp}\\t" + "%{INT:user_id}\\t%{HOSTNAME:host}\\t%{IP:client_ip}\\t%{WORD:method}\\t%{LOGLEVEL:severity}\\t%{PROG:program}\\t" + "%{GREEDYDATA:message}"; // Two timestamps: one local, one UTC Collection<String> sampleMessages = Arrays.asList( "559550912540598297\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t38545844\tserv02nw07\t192.168.114.28\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986880\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t9049724\tserv02nw03\t10.120.48.147\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912548986887\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t884343\tserv02tw03\t192.168.121.189\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp", "559550912603512850\t4/20/2016 2:06PM\t2016-04-20T21:06:53Z\t8907014\tserv02nw01\t192.168.118.208\tAuthpriv\t" + "Info\tsshd\tsubsystem request for sftp" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.singletonMap("CUSTOM_TIMESTAMP", "%{MONTHNUM}/%{MONTHDAY}/%{YEAR} %{HOUR}:%{MINUTE}(?:AM|PM)"), NOOP_TIMEOUT_CHECKER ); grokPatternCreator.validateFullLineGrokPattern(grokPattern, timestampField); assertEquals(9, mappings.size()); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("serial_no")); Map<String, String> expectedDateMapping = new HashMap<>(); expectedDateMapping.put(TextStructureUtils.MAPPING_TYPE_SETTING, "date"); expectedDateMapping.put(TextStructureUtils.MAPPING_FORMAT_SETTING, "iso8601"); assertEquals(expectedDateMapping, mappings.get("utc_timestamp")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"), mappings.get("user_id")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("host")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "ip"), mappings.get("client_ip")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("method")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("severity")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("program")); assertEquals(Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"), mappings.get("message")); } public void testValidateFullLineGrokPatternGivenInvalid() { String timestampField = "utc_timestamp"; String grokPattern = "%{INT:serial_no}\\t%{TIMESTAMP_ISO8601:local_timestamp}\\t%{TIMESTAMP_ISO8601:utc_timestamp}\\t" + "%{INT:user_id}\\t%{HOSTNAME:host}\\t%{IP:client_ip}\\t%{WORD:method}\\t%{LOGLEVEL:severity}\\t%{PROG:program}\\t" + "%{GREEDYDATA:message}"; Collection<String> sampleMessages = Arrays.asList( "Sep 8 11:55:06 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'elastic.slack.com/A/IN': 95.110.64.205#53", "Sep 8 11:55:08 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'slack-imgs.com/A/IN': 95.110.64.205#53", "Sep 8 11:55:35 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'www.elastic.co/A/IN': 95.110.68.206#53", "Sep 8 11:55:42 linux named[22529]: error (unexpected RCODE REFUSED) resolving 'b.akamaiedge.net/A/IN': 95.110.64.205#53" ); Map<String, Object> mappings = new HashMap<>(); GrokPatternCreator grokPatternCreator = new GrokPatternCreator( explanation, sampleMessages, mappings, null, Collections.emptyMap(), NOOP_TIMEOUT_CHECKER ); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> grokPatternCreator.validateFullLineGrokPattern(grokPattern, timestampField) ); assertEquals("Supplied Grok pattern [" + grokPattern + "] does not match sample messages", e.getMessage()); } }
GlenRSmith/elasticsearch
x-pack/plugin/text-structure/src/test/java/org/elasticsearch/xpack/textstructure/structurefinder/GrokPatternCreatorTests.java
Java
apache-2.0
37,348
/* * Copyright 2014 JBoss 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. */ package org.drools.workbench.models.guided.dtree.shared.model.nodes; public interface TypeNode extends BoundNode { String getClassName(); void setClassName( final String className ); }
ThiagoGarciaAlves/drools
drools-workbench-models/drools-workbench-models-guided-dtree/src/main/java/org/drools/workbench/models/guided/dtree/shared/model/nodes/TypeNode.java
Java
apache-2.0
791
/* * Copyright 2011 gitblit.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. */ package com.gitblit.utils; import static org.eclipse.jgit.lib.Constants.encode; import static org.eclipse.jgit.lib.Constants.encodeASCII; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.MessageFormat; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.util.RawParseUtils; import com.gitblit.models.PathModel.PathChangeModel; import com.gitblit.utils.DiffUtils.DiffStat; /** * Generates an html snippet of a diff in Gitblit's style, tracks changed paths, * and calculates diff stats. * * @author James Moger * */ public class GitBlitDiffFormatter extends DiffFormatter { private final OutputStream os; private final DiffStat diffStat; private PathChangeModel currentPath; private int left, right; public GitBlitDiffFormatter(OutputStream os, String commitId) { super(os); this.os = os; this.diffStat = new DiffStat(commitId); } @Override public void format(DiffEntry ent) throws IOException { currentPath = diffStat.addPath(ent); super.format(ent); } /** * Output a hunk header * * @param aStartLine * within first source * @param aEndLine * within first source * @param bStartLine * within second source * @param bEndLine * within second source * @throws IOException */ @Override protected void writeHunkHeader(int aStartLine, int aEndLine, int bStartLine, int bEndLine) throws IOException { os.write("<tr><th>..</th><th>..</th><td class='hunk_header'>".getBytes()); os.write('@'); os.write('@'); writeRange('-', aStartLine + 1, aEndLine - aStartLine); writeRange('+', bStartLine + 1, bEndLine - bStartLine); os.write(' '); os.write('@'); os.write('@'); os.write("</td></tr>\n".getBytes()); left = aStartLine + 1; right = bStartLine + 1; } protected void writeRange(final char prefix, final int begin, final int cnt) throws IOException { os.write(' '); os.write(prefix); switch (cnt) { case 0: // If the range is empty, its beginning number must // be the // line just before the range, or 0 if the range is // at the // start of the file stream. Here, begin is always 1 // based, // so an empty file would produce "0,0". // os.write(encodeASCII(begin - 1)); os.write(','); os.write('0'); break; case 1: // If the range is exactly one line, produce only // the number. // os.write(encodeASCII(begin)); break; default: os.write(encodeASCII(begin)); os.write(','); os.write(encodeASCII(cnt)); break; } } @Override protected void writeLine(final char prefix, final RawText text, final int cur) throws IOException { // update entry diffstat currentPath.update(prefix); // output diff os.write("<tr>".getBytes()); switch (prefix) { case '+': os.write(("<th></th><th>" + (right++) + "</th>").getBytes()); os.write("<td><div class=\"diff add2\">".getBytes()); break; case '-': os.write(("<th>" + (left++) + "</th><th></th>").getBytes()); os.write("<td><div class=\"diff remove2\">".getBytes()); break; default: os.write(("<th>" + (left++) + "</th><th>" + (right++) + "</th>").getBytes()); os.write("<td>".getBytes()); break; } os.write(prefix); String line = text.getString(cur); line = StringUtils.escapeForHtml(line, false); os.write(encode(line)); switch (prefix) { case '+': case '-': os.write("</div>".getBytes()); break; default: os.write("</td>".getBytes()); } os.write("</tr>\n".getBytes()); } /** * Workaround function for complex private methods in DiffFormatter. This * sets the html for the diff headers. * * @return */ public String getHtml() { ByteArrayOutputStream bos = (ByteArrayOutputStream) os; String html = RawParseUtils.decode(bos.toByteArray()); String[] lines = html.split("\n"); StringBuilder sb = new StringBuilder(); boolean inFile = false; String oldnull = "a/dev/null"; for (String line : lines) { if (line.startsWith("index")) { // skip index lines } else if (line.startsWith("new file")) { // skip new file lines } else if (line.startsWith("\\ No newline")) { // skip no new line } else if (line.startsWith("---") || line.startsWith("+++")) { // skip --- +++ lines } else if (line.startsWith("diff")) { line = StringUtils.convertOctal(line); if (line.indexOf(oldnull) > -1) { // a is null, use b line = line.substring(("diff --git " + oldnull).length()).trim(); // trim b/ line = line.substring(2).trim(); } else { // use a line = line.substring("diff --git ".length()).trim(); line = line.substring(line.startsWith("\"a/") ? 3 : 2); line = line.substring(0, line.indexOf(" b/") > -1 ? line.indexOf(" b/") : line.indexOf("\"b/")).trim(); } if (line.charAt(0) == '"') { line = line.substring(1); } if (line.charAt(line.length() - 1) == '"') { line = line.substring(0, line.length() - 1); } if (inFile) { sb.append("</tbody></table></div>\n"); inFile = false; } sb.append(MessageFormat.format("<div class='header'><div class=\"diffHeader\" id=\"{0}\"><i class=\"icon-file\"></i> ", line)).append(line).append("</div></div>"); sb.append("<div class=\"diff\">"); sb.append("<table><tbody>"); inFile = true; } else { boolean gitLinkDiff = line.length() > 0 && line.substring(1).startsWith("Subproject commit"); if (gitLinkDiff) { sb.append("<tr><th></th><th></th>"); if (line.charAt(0) == '+') { sb.append("<td><div class=\"diff add2\">"); } else { sb.append("<td><div class=\"diff remove2\">"); } } sb.append(line); if (gitLinkDiff) { sb.append("</div></td></tr>"); } } } sb.append("</table></div>"); return sb.toString(); } public DiffStat getDiffStat() { return diffStat; } }
culmat/gitblit
src/main/java/com/gitblit/utils/GitBlitDiffFormatter.java
Java
apache-2.0
6,842
/** * 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.camel.component.docker.headers; import java.util.Map; import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.core.command.WaitContainerResultCallback; import org.apache.camel.component.docker.DockerConstants; import org.apache.camel.component.docker.DockerOperation; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; /** * Validates Wait Container Request headers are applied properly */ public class WaitContainerCmdHeaderTest extends BaseDockerHeaderTest<WaitContainerCmd> { @Mock private WaitContainerCmd mockObject; @Mock private WaitContainerResultCallback callback; @Test public void waitContainerHeaderTest() { String containerId = "9c09acd48a25"; Map<String, Object> headers = getDefaultParameters(); headers.put(DockerConstants.DOCKER_CONTAINER_ID, containerId); template.sendBodyAndHeaders("direct:in", "", headers); Mockito.verify(dockerClient, Mockito.times(1)).waitContainerCmd(containerId); } @Override protected void setupMocks() { Mockito.when(dockerClient.waitContainerCmd(anyString())).thenReturn(mockObject); Mockito.when(mockObject.exec(any())).thenReturn(callback); Mockito.when(callback.awaitStatusCode()).thenReturn(anyInt()); } @Override protected DockerOperation getOperation() { return DockerOperation.WAIT_CONTAINER; } }
punkhorn/camel-upstream
components/camel-docker/src/test/java/org/apache/camel/component/docker/headers/WaitContainerCmdHeaderTest.java
Java
apache-2.0
2,429
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.server.coordinator.rules; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.MinMaxPriorityQueue; import com.metamx.common.IAE; import com.metamx.emitter.EmittingLogger; import io.druid.server.coordinator.BalancerStrategy; import io.druid.server.coordinator.CoordinatorStats; import io.druid.server.coordinator.DruidCoordinator; import io.druid.server.coordinator.DruidCoordinatorRuntimeParams; import io.druid.server.coordinator.LoadPeonCallback; import io.druid.server.coordinator.ReplicationThrottler; import io.druid.server.coordinator.ServerHolder; import io.druid.timeline.DataSegment; import org.joda.time.DateTime; import java.util.List; import java.util.Map; import java.util.Set; /** * LoadRules indicate the number of replicants a segment should have in a given tier. */ public abstract class LoadRule implements Rule { private static final EmittingLogger log = new EmittingLogger(LoadRule.class); private static final String assignedCount = "assignedCount"; private static final String droppedCount = "droppedCount"; @Override public CoordinatorStats run(DruidCoordinator coordinator, DruidCoordinatorRuntimeParams params, DataSegment segment) { final CoordinatorStats stats = new CoordinatorStats(); final Set<DataSegment> availableSegments = params.getAvailableSegments(); final Map<String, Integer> loadStatus = Maps.newHashMap(); int totalReplicantsInCluster = params.getSegmentReplicantLookup().getTotalReplicants(segment.getIdentifier()); for (Map.Entry<String, Integer> entry : getTieredReplicants().entrySet()) { final String tier = entry.getKey(); final int expectedReplicantsInTier = entry.getValue(); final int totalReplicantsInTier = params.getSegmentReplicantLookup() .getTotalReplicants(segment.getIdentifier(), tier); final int loadedReplicantsInTier = params.getSegmentReplicantLookup() .getLoadedReplicants(segment.getIdentifier(), tier); final MinMaxPriorityQueue<ServerHolder> serverQueue = params.getDruidCluster().getServersByTier(tier); if (serverQueue == null) { log.makeAlert("Tier[%s] has no servers! Check your cluster configuration!", tier).emit(); continue; } final List<ServerHolder> serverHolderList = Lists.newArrayList(serverQueue); final DateTime referenceTimestamp = params.getBalancerReferenceTimestamp(); final BalancerStrategy strategy = params.getBalancerStrategyFactory().createBalancerStrategy(referenceTimestamp); if (availableSegments.contains(segment)) { CoordinatorStats assignStats = assign( params.getReplicationManager(), tier, totalReplicantsInCluster, expectedReplicantsInTier, totalReplicantsInTier, strategy, serverHolderList, segment ); stats.accumulate(assignStats); totalReplicantsInCluster += assignStats.getPerTierStats().get(assignedCount).get(tier).get(); } loadStatus.put(tier, expectedReplicantsInTier - loadedReplicantsInTier); } // Remove over-replication stats.accumulate(drop(loadStatus, segment, params)); return stats; } private CoordinatorStats assign( final ReplicationThrottler replicationManager, final String tier, final int totalReplicantsInCluster, final int expectedReplicantsInTier, final int totalReplicantsInTier, final BalancerStrategy strategy, final List<ServerHolder> serverHolderList, final DataSegment segment ) { final CoordinatorStats stats = new CoordinatorStats(); stats.addToTieredStat(assignedCount, tier, 0); int currReplicantsInTier = totalReplicantsInTier; int currTotalReplicantsInCluster = totalReplicantsInCluster; while (currReplicantsInTier < expectedReplicantsInTier) { boolean replicate = currTotalReplicantsInCluster > 0; if (replicate && !replicationManager.canCreateReplicant(tier)) { break; } final ServerHolder holder = strategy.findNewSegmentHomeReplicator(segment, serverHolderList); if (holder == null) { log.warn( "Not enough [%s] servers or node capacity to assign segment[%s]! Expected Replicants[%d]", tier, segment.getIdentifier(), expectedReplicantsInTier ); break; } if (replicate) { replicationManager.registerReplicantCreation( tier, segment.getIdentifier(), holder.getServer().getHost() ); } holder.getPeon().loadSegment( segment, new LoadPeonCallback() { @Override public void execute() { replicationManager.unregisterReplicantCreation( tier, segment.getIdentifier(), holder.getServer().getHost() ); } } ); stats.addToTieredStat(assignedCount, tier, 1); ++currReplicantsInTier; ++currTotalReplicantsInCluster; } return stats; } private CoordinatorStats drop( final Map<String, Integer> loadStatus, final DataSegment segment, final DruidCoordinatorRuntimeParams params ) { CoordinatorStats stats = new CoordinatorStats(); // Make sure we have enough loaded replicants in the correct tiers in the cluster before doing anything for (Integer leftToLoad : loadStatus.values()) { if (leftToLoad > 0) { return stats; } } final ReplicationThrottler replicationManager = params.getReplicationManager(); // Find all instances of this segment across tiers Map<String, Integer> replicantsByTier = params.getSegmentReplicantLookup().getClusterTiers(segment.getIdentifier()); for (Map.Entry<String, Integer> entry : replicantsByTier.entrySet()) { final String tier = entry.getKey(); int loadedNumReplicantsForTier = entry.getValue(); int expectedNumReplicantsForTier = getNumReplicants(tier); stats.addToTieredStat(droppedCount, tier, 0); MinMaxPriorityQueue<ServerHolder> serverQueue = params.getDruidCluster().get(tier); if (serverQueue == null) { log.makeAlert("No holders found for tier[%s]", entry.getKey()).emit(); continue; } List<ServerHolder> droppedServers = Lists.newArrayList(); while (loadedNumReplicantsForTier > expectedNumReplicantsForTier) { final ServerHolder holder = serverQueue.pollLast(); if (holder == null) { log.warn("Wtf, holder was null? I have no servers serving [%s]?", segment.getIdentifier()); break; } if (holder.isServingSegment(segment)) { if (expectedNumReplicantsForTier > 0) { // don't throttle unless we are removing extra replicants if (!replicationManager.canDestroyReplicant(tier)) { serverQueue.add(holder); break; } replicationManager.registerReplicantTermination( tier, segment.getIdentifier(), holder.getServer().getHost() ); } holder.getPeon().dropSegment( segment, new LoadPeonCallback() { @Override public void execute() { replicationManager.unregisterReplicantTermination( tier, segment.getIdentifier(), holder.getServer().getHost() ); } } ); --loadedNumReplicantsForTier; stats.addToTieredStat(droppedCount, tier, 1); } droppedServers.add(holder); } serverQueue.addAll(droppedServers); } return stats; } protected void validateTieredReplicants(Map<String, Integer> tieredReplicants){ if(tieredReplicants.size() == 0) throw new IAE("A rule with empty tiered replicants is invalid"); for (Map.Entry<String, Integer> entry: tieredReplicants.entrySet()) { if (entry.getValue() == null) throw new IAE("Replicant value cannot be empty"); if (entry.getValue() < 0) throw new IAE("Replicant value [%d] is less than 0, which is not allowed", entry.getValue()); } } public abstract Map<String, Integer> getTieredReplicants(); public abstract int getNumReplicants(String tier); }
tubemogul/druid
server/src/main/java/io/druid/server/coordinator/rules/LoadRule.java
Java
apache-2.0
9,453
/* * 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.deltaspike.core.util; import org.apache.deltaspike.core.spi.activation.Deactivatable; import javax.enterprise.inject.Typed; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.logging.Logger; /** * Allows handling the lookup (with fallbacks) in a central place. * See DELTASPIKE-97 */ @Typed() public abstract class ServiceUtils { private static final Logger LOG = Logger.getLogger(ServiceUtils.class.getName()); private ServiceUtils() { // prevent instantiation } public static <T> List<T> loadServiceImplementations(Class<T> serviceType) { return loadServiceImplementations(serviceType, false); } public static <T> List<T> loadServiceImplementations(Class<T> serviceType, boolean ignoreServicesWithMissingDependencies) { List<T> result = new ArrayList<T>(); Iterator<T> servicesIterator = ServiceLoader.load(serviceType).iterator(); if (!servicesIterator.hasNext()) { ClassLoader fallbackClassLoader = ServiceUtils.class.getClassLoader(); servicesIterator = ServiceLoader.load(serviceType, fallbackClassLoader).iterator(); } while (servicesIterator.hasNext()) { try { T service = servicesIterator.next(); if (service instanceof Deactivatable && !ClassDeactivationUtils.isActivated((Class<? extends Deactivatable>) service.getClass())) { LOG.info("deactivated service: " + service.getClass().getName()); continue; } result.add(service); } catch (Throwable t) { if (!ignoreServicesWithMissingDependencies) { throw ExceptionUtils.throwAsRuntimeException(t); } else { LOG.info("service filtered - caused by " + t.getMessage()); } } } return result; } }
rdicroce/deltaspike
deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ServiceUtils.java
Java
apache-2.0
3,022
/* * 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 jena; import static org.apache.jena.atlas.logging.LogCtl.setCmdLogging; import java.net.*; import java.io.*; import org.apache.jena.rdf.model.* ; import org.apache.jena.shared.JenaException ; /** A program which read an RDF model and copy it to the standard output stream. * * <p>This program will read an RDF model, in a variety of languages, * and copy it to the output stream in a possibly different language. * Input can be read either from a URL or from a file. * The program writes its results to the standard output stream and sets * its exit code to 0 if the program terminate normally, and * to -1 if it encounters an error.</p> * * <p></p> * * <pre>java jena.rdfcopy model [inlang [outlang]] * * model1 and model2 can be file names or URL's * inlang and outlang specify the language of the input and output * respectively and can be: * RDF/XML * N-TRIPLE * TURTLE * N3 * The input language defaults to RDF/XML and the output language * defaults to N-TRIPLE. * </pre> */ public class rdfcopy extends java.lang.Object { static { setCmdLogging(); } /** * @param args the command line arguments */ public static void main(String ... args) { if ( ( args.length < 1 ) || ( "-h".equals(args[0]) ) ) { usage(); System.exit(-1); } String in = args[0]; String inlang = "RDF/XML"; int j; for (j = 1; j < args.length && args[j].contains( "=" ); j++) {} int lastInProp = j; if (j < args.length) { inlang = args[j]; } j++; String outlang = "N-TRIPLE"; for (; j < args.length && args[j].contains( "=" ); j++) {} int lastOutProp = j; if (j < args.length) { outlang = args[j]; } if (j + 1 < args.length) { // System.err.println(j+"<<"+args.length); usage(); System.exit(-1); } try { Model m = ModelFactory.createDefaultModel(); String base = in ; RDFReader rdr = m.getReader(inlang); for (j = 1; j < lastInProp; j++) { int eq = args[j].indexOf("="); rdr.setProperty( args[j].substring(0, eq), args[j].substring(eq + 1)); } try { rdr.read(m, in); } catch (JenaException ex) { if ( ! ( ex.getCause() instanceof MalformedURLException ) ) throw ex ; // Tried as a URL. Try as a file name. // Make absolute File f = new File(in) ; base = "file:///"+f.getCanonicalPath().replace('\\','/') ; rdr.read(m, new FileInputStream(in), base) ; } RDFWriter w = m.getWriter(outlang); j++; for (; j < lastOutProp; j++) { int eq = args[j].indexOf("="); w.setProperty( args[j].substring(0, eq), args[j].substring(eq + 1)); } w.write(m, System.out, null) ; System.exit(0); } catch (Exception e) { System.err.println("Unhandled exception:"); System.err.println(" " + e.toString()); System.exit(-1); } } protected static void usage() { System.err.println("usage:"); System.err.println(" java jena.rdfcopy in {inprop=inval}* [ inlang {outprop=outval}* outlang]]"); System.err.println(); System.err.println(" in can be a URL or a filename"); System.err.println(" inlang and outlang can take values:"); System.err.println(" RDF/XML"); System.err.println(" RDF/XML-ABBREV"); System.err.println(" N-TRIPLE"); System.err.println(" TURTLE"); System.err.println(" N3"); System.err.println( " inlang defaults to RDF/XML, outlang to N-TRIPLE"); System.err.println(" The legal values for inprop and outprop depend on inlang and outlang."); System.err.println(" The legal values for inval and outval depend on inprop and outprop."); System.err.println(); } protected static void read(Model model, String in, String lang) throws java.io.FileNotFoundException { try { URL url = new URL(in); model.read(in, lang); } catch (java.net.MalformedURLException e) { model.read(new FileInputStream(in), "", lang); } } }
kidaa/jena
jena-core/src/main/java/jena/rdfcopy.java
Java
apache-2.0
5,015
/* * 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. */ let nativeModules = {} // for testing /** * for testing */ export function getModule (moduleName) { return nativeModules[moduleName] } /** * for testing */ export function clearModules () { nativeModules = {} } // for framework /** * init modules for an app instance * the second param determines whether to replace an existed method */ export function initModules (modules, ifReplace) { for (const moduleName in modules) { // init `modules[moduleName][]` let methods = nativeModules[moduleName] if (!methods) { methods = {} nativeModules[moduleName] = methods } // push each non-existed new method modules[moduleName].forEach(function (method) { if (typeof method === 'string') { method = { name: method } } if (!methods[method.name] || ifReplace) { methods[method.name] = method } }) } } /** * init app methods */ export function initMethods (Vm, apis) { const p = Vm.prototype for (const apiName in apis) { if (!p.hasOwnProperty(apiName)) { p[apiName] = apis[apiName] } } } /** * get a module of methods for an app instance */ export function requireModule (app, name) { const methods = nativeModules[name] const target = {} for (const methodName in methods) { Object.defineProperty(target, methodName, { configurable: true, enumerable: true, get: function moduleGetter () { return (...args) => app.callTasks({ module: name, method: methodName, args: args }) }, set: function moduleSetter (value) { if (typeof value === 'function') { return app.callTasks({ module: name, method: methodName, args: [value] }) } } }) } return target } /** * get a custom component options */ export function requireCustomComponent (app, name) { const { customComponentMap } = app return customComponentMap[name] } /** * register a custom component options */ export function registerCustomComponent (app, name, def) { const { customComponentMap } = app if (customComponentMap[name]) { console.error(`[JS Framework] define a component(${name}) that already exists`) return } customComponentMap[name] = def }
cxfeng1/incubator-weex
runtime/frameworks/legacy/app/register.js
JavaScript
apache-2.0
3,146
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.application.common.model; import org.apache.axiom.om.OMElement; import org.apache.commons.collections.CollectionUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class InboundAuthenticationRequestConfig implements Serializable { /** * */ private static final long serialVersionUID = -4619706374988196634L; private String inboundAuthKey; private String inboundAuthType; private Property[] properties = new Property[0]; /* * <InboundAuthenticationRequestConfig> <InboundAuthKey></InboundAuthKey> * <InboundAuthType></InboundAuthType> <Properties></Properties> * </InboundAuthenticationRequestConfig> */ public static InboundAuthenticationRequestConfig build( OMElement inboundAuthenticationRequestConfigOM) { if (inboundAuthenticationRequestConfigOM == null) { return null; } InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig; inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig(); Iterator<?> members = inboundAuthenticationRequestConfigOM.getChildElements(); while (members.hasNext()) { OMElement member = (OMElement) members.next(); if ("InboundAuthKey".equalsIgnoreCase(member.getLocalName())) { inboundAuthenticationRequestConfig.setInboundAuthKey(member.getText()); } else if ("InboundAuthType".equalsIgnoreCase(member.getLocalName())) { inboundAuthenticationRequestConfig.setInboundAuthType(member.getText()); } else if ("Properties".equalsIgnoreCase(member.getLocalName())) { Iterator<?> propertiesIter = member.getChildElements(); List<Property> propertiesArrList = new ArrayList<Property>(); if (propertiesIter != null) { while (propertiesIter.hasNext()) { OMElement propertiesElement = (OMElement) (propertiesIter.next()); Property prop = Property.build(propertiesElement); if (prop != null) { propertiesArrList.add(prop); } } } if (CollectionUtils.isNotEmpty(propertiesArrList)) { Property[] propertiesArr = propertiesArrList.toArray(new Property[0]); inboundAuthenticationRequestConfig.setProperties(propertiesArr); } } } return inboundAuthenticationRequestConfig; } /** * @return */ public String getInboundAuthKey() { return inboundAuthKey; } /** * @param inboundAuthKey */ public void setInboundAuthKey(String inboundAuthKey) { this.inboundAuthKey = inboundAuthKey; } /** * @return */ public String getInboundAuthType() { return inboundAuthType; } /** * @param inboundAuthType */ public void setInboundAuthType(String inboundAuthType) { this.inboundAuthType = inboundAuthType; } /** * @return */ public Property[] getProperties() { return properties; } /** * @param properties */ public void setProperties(Property[] properties) { if (properties == null) { return; } Set<Property> propertySet = new HashSet<Property>(Arrays.asList(properties)); this.properties = propertySet.toArray(new Property[propertySet.size()]); } }
kasungayan/carbon-identity
components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/InboundAuthenticationRequestConfig.java
Java
apache-2.0
4,407
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- using System; using System.Net; using System.Net.Http; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Commands.Common.Authentication.Factories; namespace Microsoft.WindowsAzure.Commands.Utilities.Websites { public abstract class KuduRemoteClientBase { /// <summary> /// Parameterless constructor for mocking /// </summary> protected KuduRemoteClientBase() { } protected KuduRemoteClientBase( string serviceUrl, ICredentials credentials = null, HttpMessageHandler handler = null) { if (serviceUrl == null) { throw new ArgumentNullException("serviceUrl"); } ServiceUrl = GeneralUtilities.EnsureTrailingSlash(serviceUrl); Credentials = credentials; if (credentials != null) { Client = AzureSession.Instance.ClientFactory.CreateHttpClient(serviceUrl, ClientFactory.CreateHttpClientHandler(serviceUrl, credentials)); } else { Client = AzureSession.Instance.ClientFactory.CreateHttpClient(serviceUrl, handler); } } public string ServiceUrl { get; private set; } public ICredentials Credentials { get; private set; } public HttpClient Client { get; private set; } } }
atpham256/azure-powershell
src/ServiceManagement/Services/Commands.Utilities/Websites/KuduRemoteClientBase.cs
C#
apache-2.0
2,292
/* * 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.cassandra.utils; import java.io.DataInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.AbstractSerializationsTester; import org.apache.cassandra.Util; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.io.util.DataInputPlus.DataInputStreamPlus; import org.apache.cassandra.io.util.DataOutputStreamPlus; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.Murmur3Partitioner; import java.io.File; import java.io.FileInputStream; public class SerializationsTest extends AbstractSerializationsTester { @BeforeClass public static void initDD() { DatabaseDescriptor.daemonInitialization(); } private static void testBloomFilterWrite(boolean offheap) throws IOException { IPartitioner partitioner = Util.testPartitioner(); try (IFilter bf = FilterFactory.getFilter(1000000, 0.0001, offheap)) { for (int i = 0; i < 100; i++) bf.add(partitioner.decorateKey(partitioner.getTokenFactory().toByteArray(partitioner.getRandomToken()))); try (DataOutputStreamPlus out = getOutput("3.0", "utils.BloomFilter.bin")) { FilterFactory.serialize(bf, out); } } } private static void testBloomFilterWrite1000(boolean offheap) throws IOException { try (IFilter bf = FilterFactory.getFilter(1000000, 0.0001, offheap)) { for (int i = 0; i < 1000; i++) bf.add(Util.dk(Int32Type.instance.decompose(i))); try (DataOutputStreamPlus out = getOutput("3.0", "utils.BloomFilter1000.bin")) { FilterFactory.serialize(bf, out); } } } @Test public void testBloomFilterRead1000() throws IOException { if (EXECUTE_WRITES) testBloomFilterWrite1000(true); try (DataInputStream in = getInput("3.0", "utils.BloomFilter1000.bin"); IFilter filter = FilterFactory.deserialize(in, true)) { boolean present; for (int i = 0 ; i < 1000 ; i++) { present = filter.isPresent(Util.dk(Int32Type.instance.decompose(i))); Assert.assertTrue(present); } for (int i = 1000 ; i < 2000 ; i++) { present = filter.isPresent(Util.dk(Int32Type.instance.decompose(i))); Assert.assertFalse(present); } } } @Test public void testBloomFilterTable() throws Exception { testBloomFilterTable("test/data/bloom-filter/la/foo/la-1-big-Filter.db"); } private static void testBloomFilterTable(String file) throws Exception { Murmur3Partitioner partitioner = new Murmur3Partitioner(); try (DataInputStream in = new DataInputStream(new FileInputStream(new File(file))); IFilter filter = FilterFactory.deserialize(in, true)) { for (int i = 1; i <= 10; i++) { DecoratedKey decoratedKey = partitioner.decorateKey(Int32Type.instance.decompose(i)); boolean present = filter.isPresent(decoratedKey); Assert.assertTrue(present); } int positives = 0; for (int i = 11; i <= 1000010; i++) { DecoratedKey decoratedKey = partitioner.decorateKey(Int32Type.instance.decompose(i)); boolean present = filter.isPresent(decoratedKey); if (present) positives++; } double fpr = positives; fpr /= 1000000; Assert.assertTrue(fpr <= 0.011d); } } private static void testEstimatedHistogramWrite() throws IOException { EstimatedHistogram hist0 = new EstimatedHistogram(); EstimatedHistogram hist1 = new EstimatedHistogram(5000); long[] offsets = new long[1000]; long[] data = new long[offsets.length + 1]; for (int i = 0; i < offsets.length; i++) { offsets[i] = i; data[i] = 10 * i; } data[offsets.length] = 100000; EstimatedHistogram hist2 = new EstimatedHistogram(offsets, data); try (DataOutputStreamPlus out = getOutput("utils.EstimatedHistogram.bin")) { EstimatedHistogram.serializer.serialize(hist0, out); EstimatedHistogram.serializer.serialize(hist1, out); EstimatedHistogram.serializer.serialize(hist2, out); } } @Test public void testEstimatedHistogramRead() throws IOException { if (EXECUTE_WRITES) testEstimatedHistogramWrite(); try (DataInputStreamPlus in = getInput("utils.EstimatedHistogram.bin")) { Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in)); Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in)); Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in)); } } }
hengxin/cassandra
test/unit/org/apache/cassandra/utils/SerializationsTest.java
Java
apache-2.0
6,082
package gitserver import ( "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "os/exec" "path/filepath" "regexp" "strings" "github.com/golang/glog" "github.com/openshift/origin/pkg/git" s2igit "github.com/openshift/source-to-image/pkg/scm/git" ) var lazyInitMatch = regexp.MustCompile("^/([^\\/]+?)/info/refs$") // lazyInitRepositoryHandler creates a handler that will initialize a Git repository // if it does not yet exist. func lazyInitRepositoryHandler(config *Config, handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { handler.ServeHTTP(w, r) return } match := lazyInitMatch.FindStringSubmatch(r.URL.Path) if match == nil { handler.ServeHTTP(w, r) return } name := match[1] if name == "." || name == ".." { handler.ServeHTTP(w, r) return } if !strings.HasSuffix(name, ".git") { name += ".git" } path := filepath.Join(config.Home, name) _, err := os.Stat(path) if !os.IsNotExist(err) { handler.ServeHTTP(w, r) return } self := RepositoryURL(config, name, r) log.Printf("Lazily initializing bare repository %s", self.String()) defaultHooks, err := loadHooks(config.HookDirectory) if err != nil { log.Printf("error: unable to load default hooks: %v", err) http.Error(w, fmt.Sprintf("unable to initialize repository: %v", err), http.StatusInternalServerError) return } // TODO: capture init hook output for Git if _, err := newRepository(config, path, defaultHooks, self, nil); err != nil { log.Printf("error: unable to initialize repo %s: %v", path, err) http.Error(w, fmt.Sprintf("unable to initialize repository: %v", err), http.StatusInternalServerError) os.RemoveAll(path) return } eventCounter.WithLabelValues(name, "init").Inc() handler.ServeHTTP(w, r) }) } // RepositoryURL creates the public URL for the named git repo. If both config.URL and // request are nil, the returned URL will be nil. func RepositoryURL(config *Config, name string, r *http.Request) *url.URL { var url url.URL switch { case config.InternalURL != nil: url = *config.InternalURL case config.URL != nil: url = *config.URL case r != nil: url = *r.URL url.Host = r.Host url.Scheme = "http" default: return nil } url.Path = "/" + name url.RawQuery = "" url.Fragment = "" return &url } func newRepository(config *Config, path string, hooks map[string]string, self *url.URL, origin *s2igit.URL) ([]byte, error) { var out []byte repo := git.NewRepositoryForBinary(config.GitBinary) barePath := path if !strings.HasSuffix(barePath, ".git") { barePath += ".git" } aliasPath := strings.TrimSuffix(barePath, ".git") if origin != nil { if err := repo.CloneMirror(barePath, origin.StringNoFragment()); err != nil { return out, err } } else { if err := repo.Init(barePath, true); err != nil { return out, err } } if self != nil { if err := repo.AddLocalConfig(barePath, "gitserver.self.url", self.String()); err != nil { return out, err } } // remove all sample hooks, ignore errors here if files, err := ioutil.ReadDir(filepath.Join(barePath, "hooks")); err == nil { for _, file := range files { os.Remove(filepath.Join(barePath, "hooks", file.Name())) } } for name, hook := range hooks { dest := filepath.Join(barePath, "hooks", name) if err := os.Remove(dest); err != nil && !os.IsNotExist(err) { return out, err } glog.V(5).Infof("Creating hook symlink %s -> %s", dest, hook) if err := os.Symlink(hook, dest); err != nil { return out, err } } if initHook, ok := hooks["init"]; ok { glog.V(5).Infof("Init hook exists, invoking it") cmd := exec.Command(initHook) cmd.Dir = barePath result, err := cmd.CombinedOutput() glog.V(5).Infof("Init output:\n%s", result) if err != nil { return out, fmt.Errorf("init hook failed: %v\n%s", err, string(result)) } out = result } if err := os.Symlink(barePath, aliasPath); err != nil { return out, fmt.Errorf("cannot create alias path %s: %v", aliasPath, err) } return out, nil } // clone clones the provided git repositories func clone(config *Config) error { defaultHooks, err := loadHooks(config.HookDirectory) if err != nil { return err } errs := []error{} for name, v := range config.InitialClones { hooks := mergeHooks(defaultHooks, v.Hooks) path := filepath.Join(config.Home, name) ok, err := git.IsBareRoot(path) if err != nil { errs = append(errs, err) continue } if ok { if !config.CleanBeforeClone { continue } log.Printf("Removing %s", path) if err := os.RemoveAll(path); err != nil { errs = append(errs, err) continue } } log.Printf("Cloning %s into %s", v.URL.StringNoFragment(), path) self := RepositoryURL(config, name, nil) if _, err := newRepository(config, path, hooks, self, &v.URL); err != nil { // TODO: tear this directory down errs = append(errs, err) continue } } if len(errs) > 0 { s := []string{} for _, err := range errs { s = append(s, err.Error()) } return fmt.Errorf("initial clone failed:\n* %s", strings.Join(s, "\n* ")) } return nil } func loadHooks(path string) (map[string]string, error) { glog.V(5).Infof("Loading hooks from directory %s", path) hooks := make(map[string]string) if len(path) == 0 { return hooks, nil } files, err := ioutil.ReadDir(path) if err != nil { return nil, err } for _, file := range files { if file.IsDir() || (file.Mode().Perm()&0111) == 0 { continue } hook := filepath.Join(path, file.Name()) name := filepath.Base(hook) glog.V(5).Infof("Adding hook %s at %s", name, hook) hooks[name] = hook } return hooks, nil } func mergeHooks(hooks ...map[string]string) map[string]string { hook := make(map[string]string) for _, m := range hooks { for k, v := range m { hook[k] = v } } return hook }
wjiangjay/origin
pkg/gitserver/initializer.go
GO
apache-2.0
5,915
package com.tutsplus.vectordrawables; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
biwoodfengs/AndroidDemoProjects
VectorDrawables/app/src/androidTest/java/com/tutsplus/vectordrawables/ApplicationTest.java
Java
apache-2.0
359
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.util; import org.jboss.logging.Logger; import org.junit.Assume; import org.junit.runners.model.Statement; import org.junit.runner.Description; import org.junit.rules.ExternalResource; import org.keycloak.models.LDAPConstants; import org.keycloak.util.ldap.LDAPEmbeddedServer; import java.io.File; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Map; import java.util.Properties; import static org.keycloak.testsuite.utils.io.IOUtil.PROJECT_BUILD_DIRECTORY; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class LDAPRule extends ExternalResource { private static final Logger log = Logger.getLogger(LDAPRule.class); // Note: Be sure to annotate the testing class with the "EnableVault" annotation // to get the necessary FilePlaintext vault created automatically for the test private static final String VAULT_EXPRESSION = "${vault.ldap_bindCredential}"; public static final String LDAP_CONNECTION_PROPERTIES_LOCATION = "classpath:ldap/ldap-connection.properties"; private static final String PROPERTY_ENABLE_ACCESS_CONTROL = "enableAccessControl"; private static final String PROPERTY_ENABLE_ANONYMOUS_ACCESS = "enableAnonymousAccess"; private static final String PROPERTY_ENABLE_SSL = "enableSSL"; private static final String PROPERTY_ENABLE_STARTTLS = "enableStartTLS"; private static final String PROPERTY_KEYSTORE_FILE = "keystoreFile"; private static final String PRIVATE_KEY = "dependency/keystore/keycloak.jks"; private static final String PROPERTY_CERTIFICATE_PASSWORD = "certificatePassword"; LDAPTestConfiguration ldapTestConfiguration; private LDAPEmbeddedServer ldapEmbeddedServer; private LDAPAssume assume; protected Properties defaultProperties = new Properties(); public LDAPRule assumeTrue(LDAPAssume assume) { this.assume = assume; return this; } @Override protected void before() throws Throwable { String connectionPropsLocation = getConnectionPropertiesLocation(); ldapTestConfiguration = LDAPTestConfiguration.readConfiguration(connectionPropsLocation); Assume.assumeTrue("Assumption in LDAPRule is false. Skiping the test", assume==null || assume.assumeTrue(ldapTestConfiguration)); if (ldapTestConfiguration.isStartEmbeddedLdapServer()) { ldapEmbeddedServer = createServer(); ldapEmbeddedServer.init(); ldapEmbeddedServer.start(); } } @Override public Statement apply(Statement base, Description description) { // Default bind credential value defaultProperties.setProperty(LDAPConstants.BIND_CREDENTIAL, "secret"); // Default values of the authentication / access control method and connection encryption to use on the embedded // LDAP server upon start if not (re)set later via the LDAPConnectionParameters annotation directly on the test defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_ACCESS_CONTROL, "true"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_ANONYMOUS_ACCESS, "false"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_SSL, "true"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_STARTTLS, "false"); // Default LDAP server confidentiality required value defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_SET_CONFIDENTIALITY_REQUIRED, "false"); // Don't auto-update LDAP connection URL read from properties file for LDAP over SSL case even if it's wrong // (AKA don't try to guess, let the user to get it corrected in the properties file first) defaultProperties.setProperty("AUTO_UPDATE_LDAP_CONNECTION_URL", "false"); Annotation ldapConnectionAnnotation = description.getAnnotation(LDAPConnectionParameters.class); if (ldapConnectionAnnotation != null) { // Mark the LDAP connection URL as auto-adjustable to correspond to specific annotation as necessary defaultProperties.setProperty("AUTO_UPDATE_LDAP_CONNECTION_URL", "true"); LDAPConnectionParameters connectionParameters = (LDAPConnectionParameters) ldapConnectionAnnotation; // Configure the bind credential type of the LDAP rule depending on the provided annotation arguments switch (connectionParameters.bindCredential()) { case SECRET: log.debug("Setting bind credential to secret."); defaultProperties.setProperty(LDAPConstants.BIND_CREDENTIAL, "secret"); break; case VAULT: log.debug("Setting bind credential to vault."); defaultProperties.setProperty(LDAPConstants.BIND_CREDENTIAL, VAULT_EXPRESSION); break; } // Configure the authentication method of the LDAP rule depending on the provided annotation arguments switch (connectionParameters.bindType()) { case NONE: log.debug("Enabling anonymous authentication method on the LDAP server."); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_ANONYMOUS_ACCESS, "true"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_ACCESS_CONTROL, "false"); break; case SIMPLE: log.debug("Disabling anonymous authentication method on the LDAP server."); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_ANONYMOUS_ACCESS, "false"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_ACCESS_CONTROL, "true"); break; } // Configure the connection encryption of the LDAP rule depending on the provided annotation arguments switch (connectionParameters.encryption()) { case NONE: log.debug("Disabling connection encryption on the LDAP server."); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_SSL, "false"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_STARTTLS, "false"); break; case SSL: log.debug("Enabling SSL connection encryption on the LDAP server."); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_SSL, "true"); // Require the LDAP server to accept only secured connections with SSL enabled log.debug("Configuring the LDAP server to accepts only requests with a secured connection."); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_SET_CONFIDENTIALITY_REQUIRED, "true"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_STARTTLS, "false"); break; case STARTTLS: log.debug("Enabling StartTLS connection encryption on the LDAP server."); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_STARTTLS, "true"); // Require the LDAP server to accept only secured connections with StartTLS enabled log.debug("Configuring the LDAP server to accepts only requests with a secured connection."); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_SET_CONFIDENTIALITY_REQUIRED, "true"); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_SSL, "false"); break; } } return super.apply(base, description); } @Override protected void after() { try { if (ldapEmbeddedServer != null) { ldapEmbeddedServer.stop(); ldapEmbeddedServer = null; ldapTestConfiguration = null; } } catch (Exception e) { throw new RuntimeException("Error tearDown Embedded LDAP server.", e); } } protected String getConnectionPropertiesLocation() { return LDAP_CONNECTION_PROPERTIES_LOCATION; } protected LDAPEmbeddedServer createServer() { defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_DSF, LDAPEmbeddedServer.DSF_INMEMORY); defaultProperties.setProperty(LDAPEmbeddedServer.PROPERTY_LDIF_FILE, "classpath:ldap/users.ldif"); defaultProperties.setProperty(PROPERTY_CERTIFICATE_PASSWORD, "secret"); defaultProperties.setProperty(PROPERTY_KEYSTORE_FILE, new File(PROJECT_BUILD_DIRECTORY, PRIVATE_KEY).getAbsolutePath()); return new LDAPEmbeddedServer(defaultProperties); } public Map<String, String> getConfig() { Map<String, String> config = ldapTestConfiguration.getLDAPConfig(); String ldapConnectionUrl = config.get(LDAPConstants.CONNECTION_URL); if (ldapConnectionUrl != null && defaultProperties.getProperty("AUTO_UPDATE_LDAP_CONNECTION_URL").equals("true")) { if ( ldapConnectionUrl.startsWith("ldap://") && defaultProperties.getProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_SSL).equals("true") ) { // Switch protocol prefix to "ldaps://" in connection URL if LDAP over SSL is requested String updatedUrl = ldapConnectionUrl.replaceAll("ldap://", "ldaps://"); // Flip port number from LDAP to LDAPS updatedUrl = updatedUrl.replaceAll( String.valueOf(ldapEmbeddedServer.getBindPort()), String.valueOf(ldapEmbeddedServer.getBindLdapsPort()) ); config.put(LDAPConstants.CONNECTION_URL, updatedUrl); log.debugf("Using LDAP over SSL \"%s\" connection URL form over: \"%s\" since SSL connection was requested.", updatedUrl, ldapConnectionUrl); } if ( ldapConnectionUrl.startsWith("ldaps://") && !defaultProperties.getProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_SSL).equals("true") ) { // Switch protocol prefix back to "ldap://" in connection URL if LDAP over SSL flag is not set String updatedUrl = ldapConnectionUrl.replaceAll("ldaps://", "ldap://"); // Flip port number from LDAPS to LDAP updatedUrl = updatedUrl.replaceAll( String.valueOf(ldapEmbeddedServer.getBindLdapsPort()), String.valueOf(ldapEmbeddedServer.getBindPort()) ); config.put(LDAPConstants.CONNECTION_URL, updatedUrl); log.debugf("Using plaintext / startTLS \"%s\" connection URL form over: \"%s\" since plaintext / startTLS connection was requested.", updatedUrl, ldapConnectionUrl); } } switch (defaultProperties.getProperty(LDAPConstants.BIND_CREDENTIAL)) { case VAULT_EXPRESSION: config.put(LDAPConstants.BIND_CREDENTIAL, VAULT_EXPRESSION); break; } switch (defaultProperties.getProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_ANONYMOUS_ACCESS)) { case "true": config.put(LDAPConstants.AUTH_TYPE, LDAPConstants.AUTH_TYPE_NONE); break; default: // Default to username + password LDAP authentication method config.put(LDAPConstants.AUTH_TYPE, LDAPConstants.AUTH_TYPE_SIMPLE); } switch (defaultProperties.getProperty(LDAPEmbeddedServer.PROPERTY_ENABLE_STARTTLS)) { case "true": config.put(LDAPConstants.START_TLS, "true"); // Use truststore from TruststoreSPI also for StartTLS connections config.put(LDAPConstants.USE_TRUSTSTORE_SPI, LDAPConstants.USE_TRUSTSTORE_ALWAYS); break; default: // Default to startTLS disabled config.put(LDAPConstants.START_TLS, "false"); // By default use truststore from TruststoreSPI only for LDAP over SSL connections config.put(LDAPConstants.USE_TRUSTSTORE_SPI, LDAPConstants.USE_TRUSTSTORE_LDAPS_ONLY); } switch (defaultProperties.getProperty(LDAPEmbeddedServer.PROPERTY_SET_CONFIDENTIALITY_REQUIRED)) { case "true": System.setProperty("PROPERTY_SET_CONFIDENTIALITY_REQUIRED", "true"); break; default: // Configure the LDAP server to accept not secured connections from clients by default System.setProperty("PROPERTY_SET_CONFIDENTIALITY_REQUIRED", "false"); } return config; } public int getSleepTime() { return ldapTestConfiguration.getSleepTime(); } public LDAPEmbeddedServer getLdapEmbeddedServer() { return ldapEmbeddedServer; } /** Allows to run particular LDAP test just under specific conditions (eg. some test running just on Active Directory) **/ public interface LDAPAssume { boolean assumeTrue(LDAPTestConfiguration ldapConfig); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface LDAPConnectionParameters { // Default to secret as the bind credential unless annotated otherwise BindCredential bindCredential() default LDAPConnectionParameters.BindCredential.SECRET; // Disable anonymous LDAP authentication by default unless annotated otherwise BindType bindType() default LDAPConnectionParameters.BindType.SIMPLE; // Enable SSL encrypted LDAP connections (along with the unencrypted ones) by default unless annotated otherwise Encryption encryption() default LDAPConnectionParameters.Encryption.SSL; public enum BindCredential { SECRET, VAULT } public enum BindType { NONE, SIMPLE } public enum Encryption { NONE, // Important: Choosing either of "SSL" or "STARTTLS" connection encryption methods below // will also configure the LDAP server to accept only a secured connection from clients // (IOW plaintext client connections will be prohibited). Use those two options with care! SSL, STARTTLS } } }
keycloak/keycloak
testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/LDAPRule.java
Java
apache-2.0
15,403
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.aggregations.pipeline; import org.elasticsearch.common.collect.EvictingQueue; import org.elasticsearch.core.Nullable; import org.elasticsearch.search.DocValueFormat; import org.elasticsearch.search.aggregations.AggregationReduceContext; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; import org.elasticsearch.search.aggregations.bucket.histogram.HistogramFactory; import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.elasticsearch.search.aggregations.pipeline.BucketHelpers.resolveBucketValue; public class SerialDiffPipelineAggregator extends PipelineAggregator { private DocValueFormat formatter; private GapPolicy gapPolicy; private int lag; SerialDiffPipelineAggregator( String name, String[] bucketsPaths, @Nullable DocValueFormat formatter, GapPolicy gapPolicy, int lag, Map<String, Object> metadata ) { super(name, bucketsPaths, metadata); this.formatter = formatter; this.gapPolicy = gapPolicy; this.lag = lag; } @Override public InternalAggregation reduce(InternalAggregation aggregation, AggregationReduceContext reduceContext) { @SuppressWarnings("rawtypes") InternalMultiBucketAggregation< ? extends InternalMultiBucketAggregation, ? extends InternalMultiBucketAggregation.InternalBucket> histo = (InternalMultiBucketAggregation< ? extends InternalMultiBucketAggregation, ? extends InternalMultiBucketAggregation.InternalBucket>) aggregation; List<? extends InternalMultiBucketAggregation.InternalBucket> buckets = histo.getBuckets(); HistogramFactory factory = (HistogramFactory) histo; List<Bucket> newBuckets = new ArrayList<>(); EvictingQueue<Double> lagWindow = new EvictingQueue<>(lag); int counter = 0; for (InternalMultiBucketAggregation.InternalBucket bucket : buckets) { Double thisBucketValue = resolveBucketValue(histo, bucket, bucketsPaths()[0], gapPolicy); Bucket newBucket = bucket; counter += 1; // Still under the initial lag period, add nothing and move on Double lagValue; if (counter <= lag) { lagValue = Double.NaN; } else { lagValue = lagWindow.peek(); // Peek here, because we rely on add'ing to always move the window } // Normalize null's to NaN if (thisBucketValue == null) { thisBucketValue = Double.NaN; } // Both have values, calculate diff and replace the "empty" bucket if (Double.isNaN(thisBucketValue) == false && Double.isNaN(lagValue) == false) { double diff = thisBucketValue - lagValue; List<InternalAggregation> aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false) .map((p) -> (InternalAggregation) p) .collect(Collectors.toList()); aggs.add(new InternalSimpleValue(name(), diff, formatter, metadata())); newBucket = factory.createBucket(factory.getKey(bucket), bucket.getDocCount(), InternalAggregations.from(aggs)); } newBuckets.add(newBucket); lagWindow.add(thisBucketValue); } return factory.createAggregation(newBuckets); } }
GlenRSmith/elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/pipeline/SerialDiffPipelineAggregator.java
Java
apache-2.0
4,241
std_trap = trap("INT") { exit! 130 } # no backtrace thanks require "pathname" HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent.join("Homebrew") $:.unshift(HOMEBREW_LIBRARY_PATH.to_s) require "global" if ARGV == %w[--version] || ARGV == %w[-v] puts "Homebrew #{Homebrew.homebrew_version_string}" puts "Homebrew/homebrew-core #{Homebrew.core_tap_version_string}" exit 0 end if OS.mac? && MacOS.version < "10.6" abort <<-EOABORT.undent Homebrew requires Snow Leopard or higher. For Tiger and Leopard support, see: https://github.com/mistydemeo/tigerbrew EOABORT end def require?(path) require path rescue LoadError => e # HACK: ( because we should raise on syntax errors but # not if the file doesn't exist. TODO make robust! raise unless e.to_s.include? path end begin trap("INT", std_trap) # restore default CTRL-C handler empty_argv = ARGV.empty? help_flag_list = %w[-h --help --usage -? help] help_flag = false internal_cmd = true cmd = nil ARGV.dup.each_with_index do |arg, i| if help_flag && cmd break elsif help_flag_list.include? arg help_flag = true elsif !cmd cmd = ARGV.delete_at(i) end end # Add contributed commands to PATH before checking. Dir["#{HOMEBREW_LIBRARY}/Taps/*/*/cmd"].each do |tap_cmd_dir| ENV["PATH"] += "#{File::PATH_SEPARATOR}#{tap_cmd_dir}" end # Add SCM wrappers. ENV["PATH"] += "#{File::PATH_SEPARATOR}#{HOMEBREW_SHIMS_PATH}/scm" if cmd internal_cmd = require? HOMEBREW_LIBRARY_PATH.join("cmd", cmd) if !internal_cmd && ARGV.homebrew_developer? internal_cmd = require? HOMEBREW_LIBRARY_PATH.join("dev-cmd", cmd) end end # Usage instructions should be displayed if and only if one of: # - a help flag is passed AND an internal command is matched # - a help flag is passed AND there is no command specified # - no arguments are passed # # It should never affect external commands so they can handle usage # arguments themselves. if empty_argv || (help_flag && (cmd.nil? || internal_cmd)) # TODO: - `brew help cmd` should display subcommand help require "cmd/help" if empty_argv $stderr.puts ARGV.usage else puts ARGV.usage end exit ARGV.any? ? 0 : 1 end if internal_cmd Homebrew.send cmd.to_s.tr("-", "_").downcase elsif which "brew-#{cmd}" %w[CACHE LIBRARY_PATH].each do |e| ENV["HOMEBREW_#{e}"] = Object.const_get("HOMEBREW_#{e}").to_s end exec "brew-#{cmd}", *ARGV elsif (path = which("brew-#{cmd}.rb")) && require?(path) exit Homebrew.failed? ? 1 : 0 else require "tap" possible_tap = case cmd when "brewdle", "brewdler", "bundle", "bundler" Tap.fetch("Homebrew", "bundle") when "cask" Tap.fetch("caskroom", "cask") when "services" Tap.fetch("Homebrew", "services") end if possible_tap && !possible_tap.installed? brew_uid = HOMEBREW_BREW_FILE.stat.uid tap_commands = [] if Process.uid.zero? && !brew_uid.zero? tap_commands += %W[/usr/bin/sudo -u ##{brew_uid}] end tap_commands += %W[#{HOMEBREW_BREW_FILE} tap #{possible_tap}] safe_system *tap_commands exec HOMEBREW_BREW_FILE, cmd, *ARGV else onoe "Unknown command: #{cmd}" exit 1 end end rescue FormulaUnspecifiedError abort "This command requires a formula argument" rescue KegUnspecifiedError abort "This command requires a keg argument" rescue UsageError onoe "Invalid usage" abort ARGV.usage rescue SystemExit => e onoe "Kernel.exit" if ARGV.verbose? && !e.success? $stderr.puts e.backtrace if ARGV.debug? raise rescue Interrupt => e $stderr.puts # seemingly a newline is typical exit 130 rescue BuildError => e e.dump exit 1 rescue RuntimeError, SystemCallError => e raise if e.message.empty? onoe e $stderr.puts e.backtrace if ARGV.debug? exit 1 rescue Exception => e onoe e if internal_cmd $stderr.puts "#{Tty.white}Please report this bug:" $stderr.puts " #{Tty.em}#{OS::ISSUES_URL}#{Tty.reset}" end $stderr.puts e.backtrace exit 1 else exit 1 if Homebrew.failed? end
joshfriend/homebrew
Library/brew.rb
Ruby
bsd-2-clause
4,159
class Querious < Cask version 'latest' sha256 :no_check url 'http://www.araelium.com/querious/downloads/Querious.dmg' appcast 'https://store.araelium.com/updates/querious' homepage 'http://www.araelium.com/querious/' link 'Querious.app' end
NorthIsUp/homebrew-cask
Casks/querious.rb
Ruby
bsd-2-clause
255
// Copyright Louis Dionne 2013-2016 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/and.hpp> #include <boost/hana/assert.hpp> #include <boost/hana/bool.hpp> namespace hana = boost::hana; BOOST_HANA_CONSTANT_CHECK(hana::and_(hana::true_c, hana::true_c, hana::true_c, hana::true_c)); static_assert(!hana::and_(hana::true_c, false, hana::true_c, hana::true_c), ""); int main() { }
bureau14/qdb-benchmark
thirdparty/boost/libs/hana/example/and.cpp
C++
bsd-2-clause
499
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class BigJsPageSet(page_set_module.PageSet): """ Sites which load and run big JavaScript files.""" def __init__(self): super(BigJsPageSet, self).__init__( archive_data_file='data/big_js.json', bucket=page_set_module.PARTNER_BUCKET, user_agent_type='desktop') # Page sets with only one page don't work well, since we end up reusing a # renderer all the time and it keeps its memory caches alive (see # crbug.com/403735). Add a dummy second page here. urls_list = [ 'http://beta.unity3d.com/jonas/DT2/', 'http://www.foo.com', ] for url in urls_list: self.AddUserStory(page_module.Page(url, self))
markYoungH/chromium.src
tools/perf/page_sets/big_js.py
Python
bsd-3-clause
935
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/user_authenticator.h" #include <Security/Security.h> #include <string> #include "base/basictypes.h" #include "base/mac/mac_logging.h" namespace remoting { namespace { class UserAuthenticatorMac : public UserAuthenticator { public: UserAuthenticatorMac() {} virtual ~UserAuthenticatorMac() {} virtual bool Authenticate(const std::string& username, const std::string& password); private: DISALLOW_COPY_AND_ASSIGN(UserAuthenticatorMac); }; const char kAuthorizationRightName[] = "system.login.tty"; bool UserAuthenticatorMac::Authenticate(const std::string& username, const std::string& password) { // The authorization right being requested. This particular right allows // testing of a username/password, as if the user were logging on to the // system locally. AuthorizationItem right; right.name = kAuthorizationRightName; right.valueLength = 0; right.value = NULL; right.flags = 0; AuthorizationRights rights; rights.count = 1; rights.items = &right; // Passing the username/password as an "environment" parameter causes these // to be submitted to the Security Framework, instead of the interactive // password prompt appearing on the host system. Valid on OS X 10.4 and // later versions. AuthorizationItem environment_items[2]; environment_items[0].name = kAuthorizationEnvironmentUsername; environment_items[0].valueLength = username.size(); environment_items[0].value = const_cast<char*>(username.data()); environment_items[0].flags = 0; environment_items[1].name = kAuthorizationEnvironmentPassword; environment_items[1].valueLength = password.size(); environment_items[1].value = const_cast<char*>(password.data()); environment_items[1].flags = 0; AuthorizationEnvironment environment; environment.count = 2; environment.items = environment_items; OSStatus status = AuthorizationCreate(&rights, &environment, kAuthorizationFlagExtendRights, NULL); switch (status) { case errAuthorizationSuccess: return true; case errAuthorizationDenied: return false; default: OSSTATUS_LOG(ERROR, status) << "AuthorizationCreate"; return false; } } } // namespace // static UserAuthenticator* UserAuthenticator::Create() { return new UserAuthenticatorMac(); } } // namespace remoting
aYukiSekiguchi/ACCESS-Chromium
remoting/host/user_authenticator_mac.cc
C++
bsd-3-clause
2,647
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (function() { // We are going to kill all of the builtins, so hold onto the ones we need. var defineGetter = Object.prototype.__defineGetter__; var defineSetter = Object.prototype.__defineSetter__; var Error = window.Error; var forEach = Array.prototype.forEach; var push = Array.prototype.push; var hasOwnProperty = Object.prototype.hasOwnProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var stringify = JSON.stringify; // Kill all of the builtins functions to give us a fairly high confidence that // the environment our bindings run in can't interfere with our code. // These are taken from the ECMAScript spec. var builtinTypes = [ Object, Function, Array, String, Boolean, Number, Math, Date, RegExp, JSON, ]; function clobber(obj, name, qualifiedName) { // Clobbering constructors would break everything. // Clobbering toString is annoying. // Clobbering __proto__ breaks in ways that grep can't find. // Clobbering function name will break because // SafeBuiltins does not support getters yet. See crbug.com/463526. // Clobbering Function.call would make it impossible to implement these tests. // Clobbering Object.valueOf breaks v8. // Clobbering %FunctionPrototype%.caller and .arguments will break because // these properties are poisoned accessors in ES6. if (name == 'constructor' || name == 'toString' || name == '__proto__' || name == 'name' && typeof obj == 'function' || qualifiedName == 'Function.call' || (obj !== Function && qualifiedName == 'Function.caller') || (obj !== Function && qualifiedName == 'Function.arguments') || qualifiedName == 'Object.valueOf') { return; } if (typeof obj[name] == 'function') { obj[name] = function() { throw new Error('Clobbered ' + qualifiedName + ' function'); }; } else { defineGetter.call(obj, name, function() { throw new Error('Clobbered ' + qualifiedName + ' getter'); }); } } forEach.call(builtinTypes, function(builtin) { var prototype = builtin.prototype; var typename = '<unknown>'; if (prototype) { typename = prototype.constructor.name; forEach.call(getOwnPropertyNames(prototype), function(name) { clobber(prototype, name, typename + '.' + name); }); } forEach.call(getOwnPropertyNames(builtin), function(name) { clobber(builtin, name, typename + '.' + name); }); if (builtin.name) clobber(window, builtin.name, 'window.' + builtin.name); }); // Codes for test results. Must match ExternallyConnectableMessagingTest::Result // in c/b/extensions/extension_messages_apitest.cc. var results = { OK: 0, NAMESPACE_NOT_DEFINED: 1, FUNCTION_NOT_DEFINED: 2, COULD_NOT_ESTABLISH_CONNECTION_ERROR: 3, OTHER_ERROR: 4, INCORRECT_RESPONSE_SENDER: 5, INCORRECT_RESPONSE_MESSAGE: 6, }; // Make the messages sent vaguely complex, but unambiguously JSON-ifiable. var kMessage = [{'a': {'b': 10}}, 20, 'c\x10\x11']; // Our tab's location. Normally this would be our document's location but if // we're an iframe it will be the location of the parent - in which case, // expect to be told. var tabLocationHref = null; if (parent == window) { tabLocationHref = document.location.href; } else { window.addEventListener('message', function listener(event) { window.removeEventListener('message', listener); tabLocationHref = event.data; }); } function checkLastError(reply) { if (!chrome.runtime.lastError) return true; var kCouldNotEstablishConnection = 'Could not establish connection. Receiving end does not exist.'; if (chrome.runtime.lastError.message == kCouldNotEstablishConnection) reply(results.COULD_NOT_ESTABLISH_CONNECTION_ERROR); else reply(results.OTHER_ERROR); return false; } function checkResponse(response, reply, expectedMessage, isApp) { // The response will be an echo of both the original message *and* the // MessageSender (with the tab field stripped down). // // First check the sender was correct. var incorrectSender = false; if (!isApp) { // Only extensions get access to a 'tab' property. if (!hasOwnProperty.call(response.sender, 'tab')) { console.warn('Expected a tab, got none'); incorrectSender = true; } if (response.sender.tab.url != tabLocationHref) { console.warn('Expected tab url ' + tabLocationHref + ' got ' + response.sender.tab.url); incorrectSender = true; } } if (hasOwnProperty.call(response.sender, 'id')) { console.warn('Expected no id, got "' + response.sender.id + '"'); incorrectSender = true; } if (response.sender.url != document.location.href) { console.warn('Expected url ' + document.location.href + ' got ' + response.sender.url); incorrectSender = true; } if (incorrectSender) { reply(results.INCORRECT_RESPONSE_SENDER); return false; } // Check the correct content was echoed. var expectedJson = stringify(expectedMessage); var actualJson = stringify(response.message); if (actualJson == expectedJson) return true; console.warn('Expected message ' + expectedJson + ' got ' + actualJson); reply(results.INCORRECT_RESPONSE_MESSAGE); return false; } function sendToBrowser(msg) { domAutomationController.send(msg); } function sendToBrowserForTlsChannelId(result) { // Because the TLS channel ID tests read the TLS either an error code or the // TLS channel ID string from the same value, they require the result code // to be sent as a string. // String() is clobbered, so coerce string creation with +. sendToBrowser("" + result); } function checkRuntime(reply) { if (!reply) reply = sendToBrowser; if (!chrome.runtime) { reply(results.NAMESPACE_NOT_DEFINED); return false; } if (!chrome.runtime.connect || !chrome.runtime.sendMessage) { reply(results.FUNCTION_NOT_DEFINED); return false; } return true; } function checkRuntimeForTlsChannelId() { return checkRuntime(sendToBrowserForTlsChannelId); } function checkTlsChannelIdResponse(response) { if (chrome.runtime.lastError) { if (chrome.runtime.lastError.message == kCouldNotEstablishConnection) sendToBrowserForTlsChannelId( results.COULD_NOT_ESTABLISH_CONNECTION_ERROR); else sendToBrowserForTlsChannelId(results.OTHER_ERROR); return; } if (response.sender.tlsChannelId !== undefined) sendToBrowserForTlsChannelId(response.sender.tlsChannelId); else sendToBrowserForTlsChannelId(''); } window.actions = { appendIframe: function(src) { var iframe = document.createElement('iframe'); // When iframe has loaded, notify it of our tab location (probably // document.location) to use in its assertions, then continue. iframe.addEventListener('load', function listener() { iframe.removeEventListener('load', listener); iframe.contentWindow.postMessage(tabLocationHref, '*'); sendToBrowser(true); }); iframe.src = src; document.body.appendChild(iframe); } }; window.assertions = { canConnectAndSendMessages: function(extensionId, isApp, message) { if (!checkRuntime()) return; if (!message) message = kMessage; function canSendMessage(reply) { chrome.runtime.sendMessage(extensionId, message, function(response) { if (checkLastError(reply) && checkResponse(response, reply, message, isApp)) { reply(results.OK); } }); } function canConnectAndSendMessages(reply) { var port = chrome.runtime.connect(extensionId); port.postMessage(message, function() { checkLastError(reply); }); port.postMessage(message, function() { checkLastError(reply); }); var pendingResponses = 2; var ok = true; port.onMessage.addListener(function(response) { pendingResponses--; ok = ok && checkLastError(reply) && checkResponse(response, reply, message, isApp); if (pendingResponses == 0 && ok) reply(results.OK); }); } canSendMessage(function(result) { if (result != results.OK) sendToBrowser(result); else canConnectAndSendMessages(sendToBrowser); }); }, trySendMessage: function(extensionId) { chrome.runtime.sendMessage(extensionId, kMessage, function(response) { // The result is unimportant. All that matters is the attempt. }); }, tryIllegalArguments: function() { // Tests that illegal arguments to messaging functions throw exceptions. // Regression test for crbug.com/472700, where they crashed the renderer. function runIllegalFunction(fun) { try { fun(); } catch(e) { return true; } console.error('Function did not throw exception: ' + fun); sendToBrowser(false); return false; } var result = runIllegalFunction(chrome.runtime.connect) && runIllegalFunction(function() { chrome.runtime.connect(''); }) && runIllegalFunction(function() { chrome.runtime.connect(42); }) && runIllegalFunction(function() { chrome.runtime.connect('', 42); }) && runIllegalFunction(function() { chrome.runtime.connect({name: 'noname'}); }) && runIllegalFunction(chrome.runtime.sendMessage) && runIllegalFunction(function() { chrome.runtime.sendMessage(''); }) && runIllegalFunction(function() { chrome.runtime.sendMessage(42); }) && runIllegalFunction(function() { chrome.runtime.sendMessage('', 42); }) && sendToBrowser(true); }, areAnyRuntimePropertiesDefined: function(names) { var result = false; if (chrome.runtime) { forEach.call(names, function(name) { if (chrome.runtime[name]) { console.log('runtime.' + name + ' is defined'); result = true; } }); } sendToBrowser(result); }, getTlsChannelIdFromPortConnect: function(extensionId, includeTlsChannelId, message) { if (!checkRuntimeForTlsChannelId()) return; if (!message) message = kMessage; var port = chrome.runtime.connect(extensionId, {'includeTlsChannelId': includeTlsChannelId}); port.onMessage.addListener(checkTlsChannelIdResponse); port.postMessage(message); }, getTlsChannelIdFromSendMessage: function(extensionId, includeTlsChannelId, message) { if (!checkRuntimeForTlsChannelId()) return; if (!message) message = kMessage; chrome.runtime.sendMessage(extensionId, message, {'includeTlsChannelId': includeTlsChannelId}, checkTlsChannelIdResponse); } }; }());
Chilledheart/chromium
chrome/test/data/extensions/api_test/messaging/externally_connectable/sites/assertions.js
JavaScript
bsd-3-clause
11,033
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.pipeline import ClientRawResponse from .. import models class FormdataOperations(object): """FormdataOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.config = config def upload_file( self, file_content, file_name, custom_headers=None, raw=False, callback=None, **operation_config): """Upload file. :param file_content: File to upload. :type file_content: Generator :param file_name: File name to upload. Name has to be spelled exactly as written here. :type file_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param callback: When specified, will be called with each chunk of data that is streamed. The callback should take two arguments, the bytes of the current chunk of data and the response object. If the data is uploading, response will be None. :type callback: Callable[Bytes, response=None] :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: Generator :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`ErrorException<fixtures.acceptancetestsbodyformdata.models.ErrorException>` """ # Construct URL url = '/formdata/stream/uploadfile' # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'multipart/form-data' if custom_headers: header_parameters.update(custom_headers) # Construct form data form_data_content = { 'fileContent': file_content, 'fileName': file_name, } # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send_formdata( request, header_parameters, form_data_content, **operation_config) if response.status_code not in [200]: raise models.ErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._client.stream_download(response, callback) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def upload_file_via_body( self, file_content, custom_headers=None, raw=False, callback=None, **operation_config): """Upload file. :param file_content: File to upload. :type file_content: Generator :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param callback: When specified, will be called with each chunk of data that is streamed. The callback should take two arguments, the bytes of the current chunk of data and the response object. If the data is uploading, response will be None. :type callback: Callable[Bytes, response=None] :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: Generator :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`ErrorException<fixtures.acceptancetestsbodyformdata.models.ErrorException>` """ # Construct URL url = '/formdata/stream/uploadfile' # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/octet-stream' if custom_headers: header_parameters.update(custom_headers) # Construct body body_content = self._client.stream_upload(file_content, callback) # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, **operation_config) if response.status_code not in [200]: raise models.ErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._client.stream_download(response, callback) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
annatisch/autorest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/operations/formdata_operations.py
Python
mit
5,590
// Copyright 2012 The Closure Library 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. /** * @fileoverview goog.events.EventTarget tester. */ goog.provide('goog.events.eventTargetTester'); goog.setTestOnly('goog.events.eventTargetTester'); goog.provide('goog.events.eventTargetTester.KeyType'); goog.setTestOnly('goog.events.eventTargetTester.KeyType'); goog.provide('goog.events.eventTargetTester.UnlistenReturnType'); goog.setTestOnly('goog.events.eventTargetTester.UnlistenReturnType'); goog.require('goog.array'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.EventTarget'); goog.require('goog.testing.asserts'); goog.require('goog.testing.recordFunction'); /** * Setup step for the test functions. This needs to be called from the * test setUp. * @param {Function} listenFn Function that, given the same signature * as goog.events.listen, will add listener to the given event * target. * @param {Function} unlistenFn Function that, given the same * signature as goog.events.unlisten, will remove listener from * the given event target. * @param {Function} unlistenByKeyFn Function that, given 2 * parameters: src and key, will remove the corresponding * listener. * @param {Function} listenOnceFn Function that, given the same * signature as goog.events.listenOnce, will add a one-time * listener to the given event target. * @param {Function} dispatchEventFn Function that, given the same * signature as goog.events.dispatchEvent, will dispatch the event * on the given event target. * @param {Function} removeAllFn Function that, given the same * signature as goog.events.removeAll, will remove all listeners * according to the contract of goog.events.removeAll. * @param {Function} getListenersFn Function that, given the same * signature as goog.events.getListeners, will retrieve listeners. * @param {Function} getListenerFn Function that, given the same * signature as goog.events.getListener, will retrieve the * listener object. * @param {Function} hasListenerFn Function that, given the same * signature as goog.events.hasListener, will determine whether * listeners exist. * @param {goog.events.eventTargetTester.KeyType} listenKeyType The * key type returned by listen call. * @param {goog.events.eventTargetTester.UnlistenReturnType} * unlistenFnReturnType * Whether we should check return value from * unlisten call. If unlisten does not return a value, this should * be set to false. * @param {boolean} objectListenerSupported Whether listener of type * Object is supported. */ goog.events.eventTargetTester.setUp = function( listenFn, unlistenFn, unlistenByKeyFn, listenOnceFn, dispatchEventFn, removeAllFn, getListenersFn, getListenerFn, hasListenerFn, listenKeyType, unlistenFnReturnType, objectListenerSupported) { listen = listenFn; unlisten = unlistenFn; unlistenByKey = unlistenByKeyFn; listenOnce = listenOnceFn; dispatchEvent = dispatchEventFn; removeAll = removeAllFn; getListeners = getListenersFn; getListener = getListenerFn; hasListener = hasListenerFn; keyType = listenKeyType; unlistenReturnType = unlistenFnReturnType; objectTypeListenerSupported = objectListenerSupported; listeners = []; for (var i = 0; i < goog.events.eventTargetTester.MAX_; i++) { listeners[i] = createListener(); } eventTargets = []; for (i = 0; i < goog.events.eventTargetTester.MAX_; i++) { eventTargets[i] = new goog.events.EventTarget(); } }; /** * Teardown step for the test functions. This needs to be called from * test teardown. */ goog.events.eventTargetTester.tearDown = function() { for (var i = 0; i < goog.events.eventTargetTester.MAX_; i++) { goog.dispose(eventTargets[i]); } }; /** * The type of key returned by key-returning functions (listen). * @enum {number} */ goog.events.eventTargetTester.KeyType = { /** * Returns number for key. */ NUMBER: 0, /** * Returns undefined (no return value). */ UNDEFINED: 1 }; /** * The type of unlisten function's return value. */ goog.events.eventTargetTester.UnlistenReturnType = { /** * Returns boolean indicating whether unlisten is successful. */ BOOLEAN: 0, /** * Returns undefind (no return value). */ UNDEFINED: 1 }; /** * Expando property used on "listener" function to determine if a * listener has already been checked. This is what allows us to * implement assertNoOtherListenerIsCalled. * @type {string} */ goog.events.eventTargetTester.ALREADY_CHECKED_PROP = '__alreadyChecked'; /** * Expando property used on "listener" function to record the number * of times it has been called the last time assertListenerIsCalled is * done. This allows us to verify that it has not been called more * times in assertNoOtherListenerIsCalled. */ goog.events.eventTargetTester.NUM_CALLED_PROP = '__numCalled'; /** * The maximum number of initialized event targets (in eventTargets * array) and listeners (in listeners array). * @type {number} * @private */ goog.events.eventTargetTester.MAX_ = 10; /** * Contains test event types. * @enum {string} */ var EventType = { A: goog.events.getUniqueId('a'), B: goog.events.getUniqueId('b'), C: goog.events.getUniqueId('c') }; var listen, unlisten, unlistenByKey, listenOnce, dispatchEvent; var removeAll, getListeners, getListener, hasListener; var keyType, unlistenReturnType, objectTypeListenerSupported; var eventTargets, listeners; /** * Custom event object for testing. * @constructor * @extends {goog.events.Event} */ var TestEvent = function() { goog.base(this, EventType.A); }; goog.inherits(TestEvent, goog.events.Event); /** * Creates a listener that executes the given function (optional). * @param {!Function=} opt_listenerFn The optional function to execute. * @return {!Function} The listener function. */ function createListener(opt_listenerFn) { return goog.testing.recordFunction(opt_listenerFn); } /** * Asserts that the given listener is called numCount number of times. * @param {!Function} listener The listener to check. * @param {number} numCount The number of times. See also the times() * function below. */ function assertListenerIsCalled(listener, numCount) { assertEquals('Listeners is not called the correct number of times.', numCount, listener.getCallCount()); listener[goog.events.eventTargetTester.ALREADY_CHECKED_PROP] = true; listener[goog.events.eventTargetTester.NUM_CALLED_PROP] = numCount; } /** * Asserts that no other listeners, other than those verified via * assertListenerIsCalled, have been called since the last * resetListeners(). */ function assertNoOtherListenerIsCalled() { goog.array.forEach(listeners, function(l, index) { if (!l[goog.events.eventTargetTester.ALREADY_CHECKED_PROP]) { assertEquals( 'Listeners ' + index + ' is unexpectedly called.', 0, l.getCallCount()); } else { assertEquals( 'Listeners ' + index + ' is unexpectedly called.', l[goog.events.eventTargetTester.NUM_CALLED_PROP], l.getCallCount()); } }); } /** * Resets all listeners call count to 0. */ function resetListeners() { goog.array.forEach(listeners, function(l) { l.reset(); l[goog.events.eventTargetTester.ALREADY_CHECKED_PROP] = false; }); } /** * The number of times a listener should have been executed. This * exists to make assertListenerIsCalled more readable. This is used * like so: assertListenerIsCalled(listener, times(2)); * @param {number} n The number of times a listener should have been * executed. * @return {number} The number n. */ function times(n) { return n; } function testNoListener() { dispatchEvent(eventTargets[0], EventType.A); assertNoOtherListenerIsCalled(); } function testOneListener() { listen(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.B); dispatchEvent(eventTargets[0], EventType.C); assertNoOtherListenerIsCalled(); } function testTwoListenersOfSameType() { var key1 = listen(eventTargets[0], EventType.A, listeners[0]); var key2 = listen(eventTargets[0], EventType.A, listeners[1]); if (keyType == goog.events.eventTargetTester.KeyType.NUMBER) { assertNotEquals(key1, key2); } else { assertUndefined(key1); assertUndefined(key2); } dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertNoOtherListenerIsCalled(); } function testInstallingSameListeners() { var key1 = listen(eventTargets[0], EventType.A, listeners[0]); var key2 = listen(eventTargets[0], EventType.A, listeners[0]); var key3 = listen(eventTargets[0], EventType.B, listeners[0]); if (keyType == goog.events.eventTargetTester.KeyType.NUMBER) { assertEquals(key1, key2); assertNotEquals(key1, key3); } else { assertUndefined(key1); assertUndefined(key2); assertUndefined(key3); } dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); dispatchEvent(eventTargets[0], EventType.B); assertListenerIsCalled(listeners[0], times(2)); assertNoOtherListenerIsCalled(); } function testScope() { listeners[0] = createListener(function(e) { assertEquals('Wrong scope with undefined scope', eventTargets[0], this); }); listeners[1] = createListener(function(e) { assertEquals('Wrong scope with null scope', eventTargets[0], this); }); var scope = {}; listeners[2] = createListener(function(e) { assertEquals('Wrong scope with specific scope object', scope, this); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1], false, null); listen(eventTargets[0], EventType.A, listeners[2], false, scope); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); } function testDispatchEventDoesNotThrowWithDisposedEventTarget() { goog.dispose(eventTargets[0]); assertTrue(dispatchEvent(eventTargets[0], EventType.A)); } function testDispatchEventWithObjectLiteral() { listen(eventTargets[0], EventType.A, listeners[0]); assertTrue(dispatchEvent(eventTargets[0], {type: EventType.A})); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); } function testDispatchEventWithCustomEventObject() { listen(eventTargets[0], EventType.A, listeners[0]); var e = new TestEvent(); assertTrue(dispatchEvent(eventTargets[0], e)); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); var actualEvent = listeners[0].getLastCall().getArgument(0); assertEquals(e, actualEvent); assertEquals(eventTargets[0], actualEvent.target); } function testDisposingEventTargetRemovesListeners() { listen(eventTargets[0], EventType.A, listeners[0]); goog.dispose(eventTargets[0]); dispatchEvent(eventTargets[0], EventType.A); assertNoOtherListenerIsCalled(); } /** * Unlisten/unlistenByKey should still work after disposal. There are * many circumstances when this is actually necessary. For example, a * user may have listened to an event target and stored the key * (e.g. in a goog.events.EventHandler) and only unlisten after the * target has been disposed. */ function testUnlistenWorksAfterDisposal() { var key = listen(eventTargets[0], EventType.A, listeners[0]); goog.dispose(eventTargets[0]); unlisten(eventTargets[0], EventType.A, listeners[1]); if (unlistenByKey) { unlistenByKey(eventTargets[0], key); } } function testRemovingListener() { var ret1 = unlisten(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[0]); var ret2 = unlisten(eventTargets[0], EventType.A, listeners[1]); var ret3 = unlisten(eventTargets[0], EventType.B, listeners[0]); var ret4 = unlisten(eventTargets[1], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); var ret5 = unlisten(eventTargets[0], EventType.A, listeners[0]); var ret6 = unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); if (unlistenReturnType == goog.events.eventTargetTester.UnlistenReturnType.BOOLEAN) { assertFalse(ret1); assertFalse(ret2); assertFalse(ret3); assertFalse(ret4); assertTrue(ret5); assertFalse(ret6); } else { assertUndefined(ret1); assertUndefined(ret2); assertUndefined(ret3); assertUndefined(ret4); assertUndefined(ret5); assertUndefined(ret6); } } function testCapture() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); eventTargets[9].setParentEventTarget(eventTargets[0]); var ordering = 0; listeners[0] = createListener( function(e) { assertEquals(eventTargets[2], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('First capture listener is not called first', 0, ordering); ordering++; }); listeners[1] = createListener( function(e) { assertEquals(eventTargets[1], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('2nd capture listener is not called 2nd', 1, ordering); ordering++; }); listeners[2] = createListener( function(e) { assertEquals(eventTargets[0], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('3rd capture listener is not called 3rd', 2, ordering); ordering++; }); listen(eventTargets[2], EventType.A, listeners[0], true); listen(eventTargets[1], EventType.A, listeners[1], true); listen(eventTargets[0], EventType.A, listeners[2], true); // These should not be called. listen(eventTargets[3], EventType.A, listeners[3], true); listen(eventTargets[0], EventType.B, listeners[4], true); listen(eventTargets[0], EventType.C, listeners[5], true); listen(eventTargets[1], EventType.B, listeners[6], true); listen(eventTargets[1], EventType.C, listeners[7], true); listen(eventTargets[2], EventType.B, listeners[8], true); listen(eventTargets[2], EventType.C, listeners[9], true); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testBubble() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); eventTargets[9].setParentEventTarget(eventTargets[0]); var ordering = 0; listeners[0] = createListener( function(e) { assertEquals(eventTargets[0], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('First bubble listener is not called first', 0, ordering); ordering++; }); listeners[1] = createListener( function(e) { assertEquals(eventTargets[1], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('2nd bubble listener is not called 2nd', 1, ordering); ordering++; }); listeners[2] = createListener( function(e) { assertEquals(eventTargets[2], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('3rd bubble listener is not called 3rd', 2, ordering); ordering++; }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[1], EventType.A, listeners[1]); listen(eventTargets[2], EventType.A, listeners[2]); // These should not be called. listen(eventTargets[3], EventType.A, listeners[3]); listen(eventTargets[0], EventType.B, listeners[4]); listen(eventTargets[0], EventType.C, listeners[5]); listen(eventTargets[1], EventType.B, listeners[6]); listen(eventTargets[1], EventType.C, listeners[7]); listen(eventTargets[2], EventType.B, listeners[8]); listen(eventTargets[2], EventType.C, listeners[9]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testCaptureAndBubble() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[1], EventType.A, listeners[1], true); listen(eventTargets[2], EventType.A, listeners[2], true); listen(eventTargets[0], EventType.A, listeners[3]); listen(eventTargets[1], EventType.A, listeners[4]); listen(eventTargets[2], EventType.A, listeners[5]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertListenerIsCalled(listeners[3], times(1)); assertListenerIsCalled(listeners[4], times(1)); assertListenerIsCalled(listeners[5], times(1)); assertNoOtherListenerIsCalled(); } function testPreventDefaultByReturningFalse() { listeners[0] = createListener(function(e) { return false; }); listeners[1] = createListener(function(e) { return true; }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); var result = dispatchEvent(eventTargets[0], EventType.A); assertFalse(result); } function testPreventDefault() { listeners[0] = createListener(function(e) { e.preventDefault(); }); listeners[1] = createListener(function(e) { return true; }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); var result = dispatchEvent(eventTargets[0], EventType.A); assertFalse(result); } function testPreventDefaultAtCapture() { listeners[0] = createListener(function(e) { e.preventDefault(); }); listeners[1] = createListener(function(e) { return true; }); listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1], true); var result = dispatchEvent(eventTargets[0], EventType.A); assertFalse(result); } function testStopPropagation() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[0] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[1], EventType.A, listeners[2]); listen(eventTargets[2], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertNoOtherListenerIsCalled(); } function testStopPropagation2() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[1] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[1], EventType.A, listeners[2]); listen(eventTargets[2], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertNoOtherListenerIsCalled(); } function testStopPropagation3() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[2] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[1], EventType.A, listeners[2]); listen(eventTargets[2], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testStopPropagationAtCapture() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[0] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[2], EventType.A, listeners[0], true); listen(eventTargets[1], EventType.A, listeners[1], true); listen(eventTargets[0], EventType.A, listeners[2], true); listen(eventTargets[0], EventType.A, listeners[3]); listen(eventTargets[1], EventType.A, listeners[4]); listen(eventTargets[2], EventType.A, listeners[5]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); } function testHandleEvent() { if (!objectTypeListenerSupported) { return; } var obj = {}; obj.handleEvent = goog.testing.recordFunction(); listen(eventTargets[0], EventType.A, obj); dispatchEvent(eventTargets[0], EventType.A); assertEquals(1, obj.handleEvent.getCallCount()); } function testListenOnce() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0], true); listenOnce(eventTargets[0], EventType.A, listeners[1]); listenOnce(eventTargets[0], EventType.B, listeners[2]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(0)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(0)); assertListenerIsCalled(listeners[1], times(0)); assertListenerIsCalled(listeners[2], times(0)); dispatchEvent(eventTargets[0], EventType.B); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testUnlistenInListen() { listeners[1] = createListener( function(e) { unlisten(eventTargets[0], EventType.A, listeners[1]); unlisten(eventTargets[0], EventType.A, listeners[2]); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[0], EventType.A, listeners[2]); listen(eventTargets[0], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(0)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); } function testUnlistenByKeyInListen() { if (!unlistenByKey) { return; } var key1, key2; listeners[1] = createListener( function(e) { unlistenByKey(eventTargets[0], key1); unlistenByKey(eventTargets[0], key2); }); listen(eventTargets[0], EventType.A, listeners[0]); key1 = listen(eventTargets[0], EventType.A, listeners[1]); key2 = listen(eventTargets[0], EventType.A, listeners[2]); listen(eventTargets[0], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(0)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); } function testSetParentEventTarget() { assertNull(eventTargets[0].getParentEventTarget()); eventTargets[0].setParentEventTarget(eventTargets[1]); assertEquals(eventTargets[1], eventTargets[0].getParentEventTarget()); assertNull(eventTargets[1].getParentEventTarget()); eventTargets[0].setParentEventTarget(null); assertNull(eventTargets[0].getParentEventTarget()); } function testListenOnceAfterListenDoesNotChangeExistingListener() { if (!listenOnce) { return; } listen(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(3)); assertNoOtherListenerIsCalled(); } function testListenOnceAfterListenOnceDoesNotChangeExistingListener() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); } function testListenAfterListenOnceRemoveOnceness() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(3)); assertNoOtherListenerIsCalled(); } function testUnlistenAfterListenOnce() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); listen(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); listenOnce(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); listenOnce(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertNoOtherListenerIsCalled(); } function testRemoveAllWithType() { if (!removeAll) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[0], EventType.C, listeners[2], true); listen(eventTargets[0], EventType.C, listeners[3]); listen(eventTargets[0], EventType.B, listeners[4], true); listen(eventTargets[0], EventType.B, listeners[5], true); listen(eventTargets[0], EventType.B, listeners[6]); listen(eventTargets[0], EventType.B, listeners[7]); assertEquals(4, removeAll(eventTargets[0], EventType.B)); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.B); dispatchEvent(eventTargets[0], EventType.C); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); } function testRemoveAll() { if (!removeAll) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[0], EventType.C, listeners[2], true); listen(eventTargets[0], EventType.C, listeners[3]); listen(eventTargets[0], EventType.B, listeners[4], true); listen(eventTargets[0], EventType.B, listeners[5], true); listen(eventTargets[0], EventType.B, listeners[6]); listen(eventTargets[0], EventType.B, listeners[7]); assertEquals(8, removeAll(eventTargets[0])); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.B); dispatchEvent(eventTargets[0], EventType.C); assertNoOtherListenerIsCalled(); } function testGetListeners() { if (!getListeners) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1], true); listen(eventTargets[0], EventType.A, listeners[2]); listen(eventTargets[0], EventType.A, listeners[3]); var l = getListeners(eventTargets[0], EventType.A, true); assertEquals(2, l.length); assertEquals(listeners[0], l[0].listener); assertEquals(listeners[1], l[1].listener); l = getListeners(eventTargets[0], EventType.A, false); assertEquals(2, l.length); assertEquals(listeners[2], l[0].listener); assertEquals(listeners[3], l[1].listener); l = getListeners(eventTargets[0], EventType.B, true); assertEquals(0, l.length); } function testGetListener() { if (!getListener) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); assertNotNull(getListener(eventTargets[0], EventType.A, listeners[0], true)); assertNull( getListener(eventTargets[0], EventType.A, listeners[0], true, {})); assertNull(getListener(eventTargets[1], EventType.A, listeners[0], true)); assertNull(getListener(eventTargets[0], EventType.B, listeners[0], true)); assertNull(getListener(eventTargets[0], EventType.A, listeners[1], true)); } function testHasListener() { if (!hasListener) { return; } assertFalse(hasListener(eventTargets[0])); listen(eventTargets[0], EventType.A, listeners[0], true); assertTrue(hasListener(eventTargets[0])); assertTrue(hasListener(eventTargets[0], EventType.A)); assertTrue(hasListener(eventTargets[0], EventType.A, true)); assertTrue(hasListener(eventTargets[0], undefined, true)); assertFalse(hasListener(eventTargets[0], EventType.A, false)); assertFalse(hasListener(eventTargets[0], undefined, false)); assertFalse(hasListener(eventTargets[0], EventType.B)); assertFalse(hasListener(eventTargets[0], EventType.B, true)); assertFalse(hasListener(eventTargets[1])); } function testFiringEventBeforeDisposeInternalWorks() { /** * @extends {goog.events.EventTarget} * @constructor */ var MockTarget = function() { goog.base(this); }; goog.inherits(MockTarget, goog.events.EventTarget); MockTarget.prototype.disposeInternal = function() { dispatchEvent(this, EventType.A); goog.base(this, 'disposeInternal'); }; var t = new MockTarget(); try { listen(t, EventType.A, listeners[0]); t.dispose(); assertListenerIsCalled(listeners[0], times(1)); } catch (e) { goog.dispose(t); } } function testLoopDetection() { var target = new goog.events.EventTarget(); target.setParentEventTarget(target); try { target.dispatchEvent('string'); fail('expected error'); } catch (e) { assertContains('infinite', e.message); } }
odajima-yu/closure-rails
vendor/assets/javascripts/goog/events/eventtargettester.js
JavaScript
mit
32,410
/* * Copyright (C) 2012 The Android Open Source Project * * 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.example.android.support.appnavigation.app; import com.example.android.support.appnavigation.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class OutsideTaskActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.outside_task); } public void onViewContent(View v) { Intent intent = new Intent(Intent.ACTION_VIEW) .setType("application/x-example") .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } }
madhavanks26/com.vliesaputra.deviceinformation
src/com/vliesaputra/cordova/plugins/android/support/samples/SupportAppNavigation/src/com/example/android/support/appnavigation/app/OutsideTaskActivity.java
Java
mit
1,318
// No generics for getters and setters ({ set foo<T>(newFoo) {} })
facebook/flow
src/parser/test/flow/invalid_syntax/migrated_0012.js
JavaScript
mit
67
export const tinyNDArray: any;
markogresak/DefinitelyTyped
types/poisson-disk-sampling/src/tiny-ndarray.d.ts
TypeScript
mit
31
//------------------------------------------------------------------------------ // <copyright file="ValueOfAction.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Xsl.XsltOld { using Res = System.Xml.Utils.Res; using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; internal class ValueOfAction : CompiledAction { private const int ResultStored = 2; private int selectKey = Compiler.InvalidQueryKey; private bool disableOutputEscaping; private static Action s_BuiltInRule = new BuiltInRuleTextAction(); internal static Action BuiltInRule() { Debug.Assert(s_BuiltInRule != null); return s_BuiltInRule; } internal override void Compile(Compiler compiler) { CompileAttributes(compiler); CheckRequiredAttribute(compiler, selectKey != Compiler.InvalidQueryKey, "select"); CheckEmpty(compiler); } internal override bool CompileAttribute(Compiler compiler) { string name = compiler.Input.LocalName; string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Select)) { this.selectKey = compiler.AddQuery(value); } else if (Ref.Equal(name, compiler.Atoms.DisableOutputEscaping)) { this.disableOutputEscaping = compiler.GetYesNo(value); } else { return false; } return true; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: Debug.Assert(frame != null); Debug.Assert(frame.NodeSet != null); string value = processor.ValueOf(frame, this.selectKey); if (processor.TextEvent(value, disableOutputEscaping)) { frame.Finished(); } else { frame.StoredOutput = value; frame.State = ResultStored; } break; case ResultStored: Debug.Assert(frame.StoredOutput != null); processor.TextEvent(frame.StoredOutput); frame.Finished(); break; default: Debug.Fail("Invalid ValueOfAction execution state"); break; } } } internal class BuiltInRuleTextAction : Action { private const int ResultStored = 2; internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: Debug.Assert(frame != null); Debug.Assert(frame.NodeSet != null); string value = processor.ValueOf(frame.NodeSet.Current); if (processor.TextEvent(value, /*disableOutputEscaping:*/false)) { frame.Finished(); } else { frame.StoredOutput = value; frame.State = ResultStored; } break; case ResultStored: Debug.Assert(frame.StoredOutput != null); processor.TextEvent(frame.StoredOutput); frame.Finished(); break; default: Debug.Fail("Invalid BuiltInRuleTextAction execution state"); break; } } } }
sekcheong/referencesource
System.Data.SqlXml/System/Xml/Xsl/XsltOld/ValueOfAction.cs
C#
mit
3,999
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, Directive, ElementRef, Injector, Input, NgModule, destroyPlatform} from '@angular/core'; import {async} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import * as angular from '@angular/upgrade/src/angular_js'; import {UpgradeComponent, UpgradeModule, downgradeComponent} from '@angular/upgrade/static'; import {bootstrap, html, multiTrim} from '../test_helpers'; export function main() { describe('examples', () => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); it('should have angular 1 loaded', () => expect(angular.version.major).toBe(1)); it('should verify UpgradeAdapter example', async(() => { // This is wrapping (upgrading) an Angular 1 component to be used in an Angular 2 // component @Directive({selector: 'ng1'}) class Ng1Component extends UpgradeComponent { @Input() title: string; constructor(elementRef: ElementRef, injector: Injector) { super('ng1', elementRef, injector); } } // This is an Angular 2 component that will be downgraded @Component({ selector: 'ng2', template: 'ng2[<ng1 [title]="nameProp">transclude</ng1>](<ng-content></ng-content>)' }) class Ng2Component { @Input('name') nameProp: string; } // This module represents the Angular 2 pieces of the application @NgModule({ declarations: [Ng1Component, Ng2Component], entryComponents: [Ng2Component], imports: [BrowserModule, UpgradeModule] }) class Ng2Module { ngDoBootstrap() { /* this is a placeholder to stop the boostrapper from complaining */ } } // This module represents the Angular 1 pieces of the application const ng1Module = angular .module('myExample', []) // This is an Angular 1 component that will be upgraded .directive( 'ng1', () => { return { scope: {title: '='}, transclude: true, template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' }; }) // This is wrapping (downgrading) an Angular 2 component to be used in Angular 1 .directive( 'ng2', downgradeComponent({component: Ng2Component, inputs: ['nameProp: name']})); // This is the (Angular 1) application bootstrap element // Notice that it is actually a downgraded Angular 2 component const element = html('<ng2 name="World">project</ng2>'); // Let's use a helper function to make this simpler bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(upgrade => { expect(multiTrim(element.textContent)) .toBe('ng2[ng1[Hello World!](transclude)](project)'); }); })); }); }
awerlang/angular
modules/@angular/upgrade/test/aot/integration/examples_spec.ts
TypeScript
mit
3,443
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.nashorn.internal.objects.annotations; import static jdk.nashorn.internal.objects.annotations.Attribute.DEFAULT_ATTRIBUTES; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to specify the getter method for a JavaScript "data" property. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Getter { /** * Name of the property. If empty, the name is inferred. */ public String name() default ""; /** * Attribute flags for this setter. */ public int attributes() default DEFAULT_ATTRIBUTES; /** * Where this getter lives? */ public Where where() default Where.INSTANCE; }
rokn/Count_Words_2015
testing/openjdk2/nashorn/src/jdk/nashorn/internal/objects/annotations/Getter.java
Java
mit
2,016
<?php /** * Hoa * * * @license * * New BSD License * * Copyright © 2007-2015, Hoa community. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Hoa nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ namespace Hoa\Iterator; /** * Class \Hoa\Iterator\Glob. * * Extending the SPL GlobIterator class. * * @copyright Copyright © 2007-2015 Hoa community * @license New BSD License */ class Glob extends \GlobIterator { }
Halleck45/PhpMetricsZendServer
zray/vendor/hoa/iterator/Glob.php
PHP
mit
1,879
# testing/mock.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Import stub for mock library. NOTE: copied/adapted from SQLAlchemy master for backwards compatibility; this should be removable when Alembic targets SQLAlchemy 1.0.0 """ from __future__ import absolute_import from ..util.compat import py33 if py33: from unittest.mock import MagicMock, Mock, call, patch, ANY else: try: from mock import MagicMock, Mock, call, patch, ANY # noqa except ImportError: raise ImportError( "SQLAlchemy's test suite requires the " "'mock' library as of 0.8.2.")
pcu4dros/pandora-core
workspace/lib/python3.5/site-packages/alembic/testing/mock.py
Python
mit
791
// Type definitions for bootstrap4-toggle 3.6 // Project: https://github.com/gitbrent/bootstrap4-toggle, https://gitbrent.github.io/bootstrap4-toggle/ // Definitions by: Mitchell Grice <https://github.com/gricey432> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 /// <reference types="jquery"/> interface BootstrapToggleOptions { on?: string | undefined; off?: string | undefined; size?: string | undefined; onstyle?: string | undefined; offstyle?: string | undefined; style?: string | undefined; width?: number | string | null | undefined; height?: number | string | null | undefined; } interface JQuery { bootstrapToggle(options?: BootstrapToggleOptions): JQuery; bootstrapToggle(command: "destroy" | "on" | "off" | "toggle" | "enable" | "disable"): JQuery; }
markogresak/DefinitelyTyped
types/bootstrap4-toggle/index.d.ts
TypeScript
mit
852
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var fs = require('fs'); var morgan = require('morgan'); var routes = require('./routes/index'); var number = require('./routes/number'); var array = require('./routes/array'); var bool = require('./routes/bool'); var integer = require('./routes/int'); var string = require('./routes/string'); var byte = require('./routes/byte'); var date = require('./routes/date'); var datetime = require('./routes/datetime'); var datetimeRfc1123 = require('./routes/datetime-rfc1123'); var duration = require('./routes/duration'); var complex = require('./routes/complex'); var report = require('./routes/report'); var dictionary = require('./routes/dictionary'); var paths = require('./routes/paths'); var queries = require('./routes/queries'); var pathitem = require('./routes/pathitem'); var header = require('./routes/header'); var reqopt = require('./routes/reqopt'); var httpResponses = require('./routes/httpResponses'); var files = require('./routes/files'); var formData = require('./routes/formData'); var lros = require('./routes/lros'); var paging = require('./routes/paging'); var modelFlatten = require('./routes/model-flatten'); var azureUrl = require('./routes/azureUrl'); var azureSpecial = require('./routes/azureSpecials'); var parameterGrouping = require('./routes/azureParameterGrouping.js'); var validation = require('./routes/validation.js'); var customUri = require('./routes/customUri.js'); var xml = require('./routes/xml.js'); // XML serialization var util = require('util'); var app = express(); //set up server log var now = new Date(); var logFileName = 'AccTestServer-' + now.getHours() + now.getMinutes() + now.getSeconds() + '.log'; var testResultDir = path.join(__dirname, '../../../../TestResults'); if (!fs.existsSync(testResultDir)) { fs.mkdirSync(testResultDir); } var logfile = fs.createWriteStream(path.join(testResultDir, logFileName), {flags: 'a'}); app.use(morgan('combined', {stream: logfile})); var azurecoverage = {}; var optionalCoverage = {}; var coverage = { "getArrayNull": 0, "getArrayEmpty": 0, "putArrayEmpty": 0, "getArrayInvalid": 0, "getArrayBooleanValid": 0, "putArrayBooleanValid": 0, "getArrayBooleanWithNull": 0, "getArrayBooleanWithString": 0, "getArrayIntegerValid": 0, "putArrayIntegerValid": 0, "getArrayIntegerWithNull": 0, "getArrayIntegerWithString": 0, "getArrayLongValid": 0, "putArrayLongValid": 0, "getArrayLongWithNull": 0, "getArrayLongWithString": 0, "getArrayFloatValid": 0, "putArrayFloatValid": 0, "getArrayFloatWithNull": 0, "getArrayFloatWithString": 0, "getArrayDoubleValid": 0, "putArrayDoubleValid": 0, "getArrayDoubleWithNull": 0, "getArrayDoubleWithString": 0, "getArrayStringValid": 0, "putArrayStringValid": 0, "getArrayStringWithNull": 0, "getArrayStringWithNumber": 0, "getArrayDateValid": 0, "putArrayDateValid": 0, "getArrayDateWithNull": 0, "getArrayDateWithInvalidChars": 0, "getArrayDateTimeValid": 0, "putArrayDateTimeValid": 0, "getArrayDateTimeWithNull": 0, "getArrayDateTimeWithInvalidChars": 0, "getArrayDateTimeRfc1123Valid": 0, "putArrayDateTimeRfc1123Valid": 0, "getArrayDurationValid": 0, "putArrayDurationValid": 0, "getArrayUuidValid": 0, "getArrayUuidWithInvalidChars": 0, "putArrayUuidValid": 0, "getArrayByteValid": 0, "putArrayByteValid": 0, "getArrayByteWithNull": 0, "getArrayArrayNull": 0, "getArrayArrayEmpty": 0, "getArrayArrayItemNull": 0, "getArrayArrayItemEmpty": 0, "getArrayArrayValid": 0, "putArrayArrayValid": 0, "getArrayComplexNull": 0, "getArrayComplexEmpty": 0, "getArrayComplexItemNull": 0, "getArrayComplexItemEmpty": 0, "getArrayComplexValid": 0, "putArrayComplexValid": 0, "getArrayDictionaryNull": 0, "getArrayDictionaryEmpty": 0, "getArrayDictionaryItemNull": 0, "getArrayDictionaryItemEmpty": 0, "getArrayDictionaryValid": 0, "putArrayDictionaryValid": 0, "getBoolTrue" : 0, "putBoolTrue" : 0, "getBoolFalse" : 0, "putBoolFalse" : 0, "getBoolInvalid" : 0, "getBoolNull" : 0, "getByteNull": 0, "getByteEmpty": 0, "getByteNonAscii": 0, "putByteNonAscii": 0, "getByteInvalid": 0, "getDateNull": 0, "getDateInvalid": 0, "getDateOverflow": 0, "getDateUnderflow": 0, "getDateMax": 0, "putDateMax": 0, "getDateMin": 0, "putDateMin": 0, "getDateTimeNull": 0, "getDateTimeInvalid": 0, "getDateTimeOverflow": 0, "getDateTimeUnderflow": 0, "putDateTimeMaxUtc": 0, "getDateTimeMaxUtcLowercase": 0, "getDateTimeMaxUtcUppercase": 0, "getDateTimeMaxLocalPositiveOffsetLowercase": 0, "getDateTimeMaxLocalPositiveOffsetUppercase": 0, "getDateTimeMaxLocalNegativeOffsetLowercase": 0, "getDateTimeMaxLocalNegativeOffsetUppercase": 0, "getDateTimeMinUtc": 0, "putDateTimeMinUtc": 0, "getDateTimeMinLocalPositiveOffset": 0, "getDateTimeMinLocalNegativeOffset": 0, "getDateTimeRfc1123Null": 0, "getDateTimeRfc1123Invalid": 0, "getDateTimeRfc1123Overflow": 0, "getDateTimeRfc1123Underflow": 0, "getDateTimeRfc1123MinUtc": 0, "putDateTimeRfc1123Max": 0, "putDateTimeRfc1123Min": 0, "getDateTimeRfc1123MaxUtcLowercase": 0, "getDateTimeRfc1123MaxUtcUppercase": 0, "getIntegerNull": 0, "getIntegerInvalid": 0, "getIntegerOverflow" : 0, "getIntegerUnderflow": 0, "getLongOverflow": 0, "getLongUnderflow": 0, "putIntegerMax": 0, "putLongMax": 0, "putIntegerMin": 0, "putLongMin": 0, "getNumberNull": 0, "getFloatInvalid": 0, "getDoubleInvalid": 0, "getFloatBigScientificNotation": 0, "putFloatBigScientificNotation": 0, "getDoubleBigScientificNotation": 0, "putDoubleBigScientificNotation": 0, "getDoubleBigPositiveDecimal" : 0, "putDoubleBigPositiveDecimal" : 0, "getDoubleBigNegativeDecimal" : 0, "putDoubleBigNegativeDecimal" : 0, "getFloatSmallScientificNotation" : 0, "putFloatSmallScientificNotation" : 0, "getDoubleSmallScientificNotation" : 0, "putDoubleSmallScientificNotation" : 0, "getStringNull": 0, "putStringNull": 0, "getStringEmpty": 0, "putStringEmpty": 0, "getStringMultiByteCharacters": 0, "putStringMultiByteCharacters": 0, "getStringWithLeadingAndTrailingWhitespace" : 0, "putStringWithLeadingAndTrailingWhitespace" : 0, "getStringNotProvided": 0, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, "getComplexBasicValid": 0, "getComplexBasicEmpty": 0, "getComplexBasicNotProvided": 0, "getComplexBasicNull": 0, "getComplexBasicInvalid": 0, "putComplexPrimitiveInteger": 0, "putComplexPrimitiveLong": 0, "putComplexPrimitiveFloat": 0, "putComplexPrimitiveDouble": 0, "putComplexPrimitiveBool": 0, "putComplexPrimitiveString": 0, "putComplexPrimitiveDate": 0, "putComplexPrimitiveDateTime": 0, "putComplexPrimitiveDateTimeRfc1123": 0, "putComplexPrimitiveDuration": 0, "putComplexPrimitiveByte": 0, "getComplexPrimitiveInteger": 0, "getComplexPrimitiveLong": 0, "getComplexPrimitiveFloat": 0, "getComplexPrimitiveDouble": 0, "getComplexPrimitiveBool": 0, "getComplexPrimitiveString": 0, "getComplexPrimitiveDate": 0, "getComplexPrimitiveDateTime": 0, "getComplexPrimitiveDateTimeRfc1123": 0, "getComplexPrimitiveDuration": 0, "getComplexPrimitiveByte": 0, "putComplexArrayValid": 0, "putComplexArrayEmpty": 0, "getComplexArrayValid": 0, "getComplexArrayEmpty": 0, "getComplexArrayNotProvided": 0, "putComplexDictionaryValid": 0, "putComplexDictionaryEmpty": 0, "getComplexDictionaryValid": 0, "getComplexDictionaryEmpty": 0, "getComplexDictionaryNull": 0, "getComplexDictionaryNotProvided": 0, "putComplexInheritanceValid": 0, "getComplexInheritanceValid": 0, "putComplexPolymorphismValid": 0, "getComplexPolymorphismValid": 0, "putComplexPolymorphicRecursiveValid": 0, "getComplexPolymorphicRecursiveValid": 0, "putComplexReadOnlyPropertyValid": 0, "UrlPathsBoolFalse": 0, "UrlPathsBoolTrue": 0, "UrlPathsIntPositive": 0, "UrlPathsIntNegative": 0, "UrlPathsLongPositive": 0, "UrlPathsLongNegative": 0, "UrlPathsFloatPositive": 0, "UrlPathsFloatNegative": 0, "UrlPathsDoublePositive": 0, "UrlPathsDoubleNegative": 0, "UrlPathsStringUrlEncoded": 0, "UrlPathsStringEmpty": 0, "UrlPathsEnumValid":0, "UrlPathsByteMultiByte": 0, "UrlPathsByteEmpty": 0, "UrlPathsDateValid": 0, "UrlPathsDateTimeValid": 0, "UrlQueriesBoolFalse": 0, "UrlQueriesBoolTrue": 0, "UrlQueriesBoolNull": 0, "UrlQueriesIntPositive": 0, "UrlQueriesIntNegative": 0, "UrlQueriesIntNull": 0, "UrlQueriesLongPositive": 0, "UrlQueriesLongNegative": 0, "UrlQueriesLongNull": 0, "UrlQueriesFloatPositive": 0, "UrlQueriesFloatNegative": 0, "UrlQueriesFloatNull": 0, "UrlQueriesDoublePositive": 0, "UrlQueriesDoubleNegative": 0, "UrlQueriesDoubleNull": 0, "UrlQueriesStringUrlEncoded": 0, "UrlQueriesStringEmpty": 0, "UrlQueriesStringNull": 0, "UrlQueriesEnumValid": 0, "UrlQueriesEnumNull": 0, "UrlQueriesByteMultiByte": 0, "UrlQueriesByteEmpty": 0, "UrlQueriesByteNull": 0, "UrlQueriesDateValid": 0, "UrlQueriesDateNull": 0, "UrlQueriesDateTimeValid": 0, "UrlQueriesDateTimeNull": 0, "UrlQueriesArrayCsvNull": 0, "UrlQueriesArrayCsvEmpty": 0, "UrlQueriesArrayCsvValid": 0, //Once all the languages implement this test, the scenario counter should be reset to zero. It is currently implemented in C# and Python "UrlQueriesArrayMultiNull": 1, "UrlQueriesArrayMultiEmpty": 1, "UrlQueriesArrayMultiValid": 1, "UrlQueriesArraySsvValid": 0, "UrlQueriesArrayPipesValid": 0, "UrlQueriesArrayTsvValid": 0, "UrlPathItemGetAll": 0, "UrlPathItemGetGlobalNull": 0, "UrlPathItemGetGlobalAndLocalNull": 0, "UrlPathItemGetPathItemAndLocalNull": 0, "putDictionaryEmpty": 0, "getDictionaryNull": 0, "getDictionaryEmpty": 0, "getDictionaryInvalid": 0, "getDictionaryNullValue": 0, "getDictionaryNullkey": 0, "getDictionaryKeyEmptyString": 0, "getDictionaryBooleanValid": 0, "getDictionaryBooleanWithNull": 0, "getDictionaryBooleanWithString": 0, "getDictionaryIntegerValid": 0, "getDictionaryIntegerWithNull": 0, "getDictionaryIntegerWithString": 0, "getDictionaryLongValid": 0, "getDictionaryLongWithNull": 0, "getDictionaryLongWithString": 0, "getDictionaryFloatValid": 0, "getDictionaryFloatWithNull": 0, "getDictionaryFloatWithString": 0, "getDictionaryDoubleValid": 0, "getDictionaryDoubleWithNull": 0, "getDictionaryDoubleWithString": 0, "getDictionaryStringValid": 0, "getDictionaryStringWithNull": 0, "getDictionaryStringWithNumber": 0, "getDictionaryDateValid": 0, "getDictionaryDateWithNull": 0, "getDictionaryDateWithInvalidChars": 0, "getDictionaryDateTimeValid": 0, "getDictionaryDateTimeWithNull": 0, "getDictionaryDateTimeWithInvalidChars": 0, "getDictionaryDateTimeRfc1123Valid": 0, "getDictionaryDurationValid": 0, "getDictionaryByteValid": 0, "getDictionaryByteWithNull": 0, "putDictionaryBooleanValid": 0, "putDictionaryIntegerValid": 0, "putDictionaryLongValid": 0, "putDictionaryFloatValid": 0, "putDictionaryDoubleValid": 0, "putDictionaryStringValid": 0, "putDictionaryDateValid": 0, "putDictionaryDateTimeValid": 0, "putDictionaryDateTimeRfc1123Valid": 0, "putDictionaryDurationValid": 0, "putDictionaryByteValid": 0, "getDictionaryComplexNull": 0, "getDictionaryComplexEmpty": 0, "getDictionaryComplexItemNull": 0, "getDictionaryComplexItemEmpty": 0, "getDictionaryComplexValid": 0, "putDictionaryComplexValid": 0, "getDictionaryArrayNull": 0, "getDictionaryArrayEmpty": 0, "getDictionaryArrayItemNull": 0, "getDictionaryArrayItemEmpty": 0, "getDictionaryArrayValid": 0, "putDictionaryArrayValid": 0, "getDictionaryDictionaryNull": 0, "getDictionaryDictionaryEmpty": 0, "getDictionaryDictionaryItemNull": 0, "getDictionaryDictionaryItemEmpty": 0, "getDictionaryDictionaryValid": 0, "putDictionaryDictionaryValid": 0, "putDurationPositive": 0, "getDurationNull": 0, "getDurationInvalid": 0, "getDurationPositive": 0, "HeaderParameterExistingKey": 0, "HeaderResponseExistingKey": 0, "HeaderResponseProtectedKey": 0, "HeaderParameterIntegerPositive": 0, "HeaderParameterIntegerNegative": 0, "HeaderParameterLongPositive": 0, "HeaderParameterLongNegative": 0, "HeaderParameterFloatPositive": 0, "HeaderParameterFloatNegative": 0, "HeaderParameterDoublePositive": 0, "HeaderParameterDoubleNegative": 0, "HeaderParameterBoolTrue": 0, "HeaderParameterBoolFalse": 0, "HeaderParameterStringValid": 0, "HeaderParameterStringNull": 0, "HeaderParameterStringEmpty": 0, "HeaderParameterDateValid": 0, "HeaderParameterDateMin": 0, "HeaderParameterDateTimeValid": 0, "HeaderParameterDateTimeMin": 0, "HeaderParameterDateTimeRfc1123Valid": 0, "HeaderParameterDateTimeRfc1123Min": 0, "HeaderParameterBytesValid": 0, "HeaderParameterDurationValid": 0, "HeaderResponseIntegerPositive": 0, "HeaderResponseIntegerNegative": 0, "HeaderResponseLongPositive": 0, "HeaderResponseLongNegative": 0, "HeaderResponseFloatPositive": 0, "HeaderResponseFloatNegative": 0, "HeaderResponseDoublePositive": 0, "HeaderResponseDoubleNegative": 0, "HeaderResponseBoolTrue": 0, "HeaderResponseBoolFalse": 0, "HeaderResponseStringValid": 0, "HeaderResponseStringNull": 0, "HeaderResponseStringEmpty": 0, "HeaderParameterEnumValid": 0, "HeaderParameterEnumNull": 0, "HeaderResponseEnumValid": 0, "HeaderResponseEnumNull": 0, "HeaderResponseDateValid": 0, "HeaderResponseDateMin": 0, "HeaderResponseDateTimeValid": 0, "HeaderResponseDateTimeMin": 0, "HeaderResponseDateTimeRfc1123Valid": 0, "HeaderResponseDateTimeRfc1123Min": 0, "HeaderResponseBytesValid": 0, "HeaderResponseDurationValid": 0, "FormdataStreamUploadFile": 0, "StreamUploadFile": 0, "ConstantsInPath": 0, "ConstantsInBody": 0, "CustomBaseUri": 0, //Once all the languages implement this test, the scenario counter should be reset to zero. It is currently implemented in C#, Python and node.js "CustomBaseUriMoreOptions": 1, 'getModelFlattenArray': 0, 'putModelFlattenArray': 0, 'getModelFlattenDictionary': 0, 'putModelFlattenDictionary': 0, 'getModelFlattenResourceCollection': 0, 'putModelFlattenResourceCollection': 0, 'putModelFlattenCustomBase': 0, 'postModelFlattenCustomParameter': 0, 'putModelFlattenCustomGroupedParameter': 0, /* TODO: only C#, Python and node.js support the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */ "getStringBase64Encoded": 1, "getStringBase64UrlEncoded": 1, "putStringBase64UrlEncoded": 1, "getStringNullBase64UrlEncoding": 1, "getArrayBase64Url": 1, "getDictionaryBase64Url": 1, "UrlPathsStringBase64Url": 1, "UrlPathsArrayCSVInPath": 1, /* TODO: only C# and Python support the unixtime format currently. Exclude these tests from code coverage until it is implemented in other languages */ "getUnixTime": 1, "getInvalidUnixTime": 1, "getNullUnixTime": 1, "putUnixTime": 1, "UrlPathsIntUnixTime": 1, /* TODO: Once all the languages implement these tests, the scenario counters should be reset to zero. It is currently implemented in Python */ "getDecimalInvalid": 1, "getDecimalBig": 1, "getDecimalSmall": 1, "getDecimalBigPositiveDecimal" : 1, "getDecimalBigNegativeDecimal" : 1, "putDecimalBig": 1, "putDecimalSmall": 1, "putDecimalBigPositiveDecimal" : 1, "getEnumReferenced" : 1, "putEnumReferenced" : 1, "getEnumReferencedConstant" : 1, "putEnumReferencedConstant" : 1 }; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json({strict: false})); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/bool', new bool(coverage).router); app.use('/int', new integer(coverage).router); app.use('/number', new number(coverage).router); app.use('/string', new string(coverage).router); app.use('/byte', new byte(coverage).router); app.use('/date', new date(coverage).router); app.use('/datetime', new datetime(coverage, optionalCoverage).router); app.use('/datetimeRfc1123', new datetimeRfc1123(coverage).router); app.use('/duration', new duration(coverage, optionalCoverage).router); app.use('/array', new array(coverage).router); app.use('/complex', new complex(coverage).router); app.use('/dictionary', new dictionary(coverage).router); app.use('/paths', new paths(coverage).router); app.use('/queries', new queries(coverage).router); app.use('/pathitem', new pathitem(coverage).router); app.use('/header', new header(coverage, optionalCoverage).router); app.use('/reqopt', new reqopt(coverage).router); app.use('/files', new files(coverage).router); app.use('/formdata', new formData(coverage).router); app.use('/http', new httpResponses(coverage, optionalCoverage).router); app.use('/model-flatten', new modelFlatten(coverage).router); app.use('/lro', new lros(azurecoverage).router); app.use('/paging', new paging(azurecoverage).router); app.use('/azurespecials', new azureSpecial(azurecoverage).router); app.use('/report', new report(coverage, azurecoverage).router); app.use('/subscriptions', new azureUrl(azurecoverage).router); app.use('/parameterGrouping', new parameterGrouping(azurecoverage).router); app.use('/validation', new validation(coverage).router); app.use('/customUri', new customUri(coverage).router); app.use('/xml', new xml().router); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); app.use(function(err, req, res, next) { res.status(err.status || 500); res.end(JSON.stringify(err)); }); module.exports = app;
lmazuel/autorest
src/dev/TestServer/server/app.js
JavaScript
mit
18,237
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.miio.internal.basic; /** * Various types of parameters to be send * * @author Marcel Verpaalen - Initial contribution */ public enum CommandParameterType { NONE("none"), EMPTY("empty"), ONOFF("onoff"), ONOFFPARA("onoffpara"), STRING("string"), CUSTOMSTRING("customstring"), NUMBER("number"), COLOR("color"), UNKNOWN("unknown"); private String text; CommandParameterType(String text) { this.text = text; } public static CommandParameterType fromString(String text) { for (CommandParameterType param : CommandParameterType.values()) { if (param.text.equalsIgnoreCase(text)) { return param; } } return UNKNOWN; } }
theoweiss/openhab2
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/basic/CommandParameterType.java
Java
epl-1.0
1,157
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Validator\Tests\Constraints; use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\Regex; /** * @author Bernhard Schussek <bschussek@gmail.com> */ class RegexTest extends TestCase { public function testConstraintGetDefaultOption() { $constraint = new Regex('/^[0-9]+$/'); $this->assertSame('/^[0-9]+$/', $constraint->pattern); } public function provideHtmlPatterns() { return array( // HTML5 wraps the pattern in ^(?:pattern)$ array('/^[0-9]+$/', '[0-9]+'), array('/[0-9]+$/', '.*[0-9]+'), array('/^[0-9]+/', '[0-9]+.*'), array('/[0-9]+/', '.*[0-9]+.*'), // We need a smart way to allow matching of patterns that contain // ^ and $ at various sub-clauses of an or-clause // .*(pattern).* seems to work correctly array('/[0-9]$|[a-z]+/', '.*([0-9]$|[a-z]+).*'), array('/[0-9]$|^[a-z]+/', '.*([0-9]$|^[a-z]+).*'), array('/^[0-9]|[a-z]+$/', '.*(^[0-9]|[a-z]+$).*'), // Unescape escaped delimiters array('/^[0-9]+\/$/', '[0-9]+/'), array('#^[0-9]+\#$#', '[0-9]+#'), // Cannot be converted array('/^[0-9]+$/i', null), // Inverse matches are simple, just wrap in // ((?!pattern).)* array('/^[0-9]+$/', '((?!^[0-9]+$).)*', false), array('/[0-9]+$/', '((?![0-9]+$).)*', false), array('/^[0-9]+/', '((?!^[0-9]+).)*', false), array('/[0-9]+/', '((?![0-9]+).)*', false), array('/[0-9]$|[a-z]+/', '((?![0-9]$|[a-z]+).)*', false), array('/[0-9]$|^[a-z]+/', '((?![0-9]$|^[a-z]+).)*', false), array('/^[0-9]|[a-z]+$/', '((?!^[0-9]|[a-z]+$).)*', false), array('/^[0-9]+\/$/', '((?!^[0-9]+/$).)*', false), array('#^[0-9]+\#$#', '((?!^[0-9]+#$).)*', false), array('/^[0-9]+$/i', null, false), ); } /** * @dataProvider provideHtmlPatterns */ public function testGetHtmlPattern($pattern, $htmlPattern, $match = true) { $constraint = new Regex(array( 'pattern' => $pattern, 'match' => $match, )); $this->assertSame($pattern, $constraint->pattern); $this->assertSame($htmlPattern, $constraint->getHtmlPattern()); } public function testGetCustomHtmlPattern() { $constraint = new Regex(array( 'pattern' => '((?![0-9]$|[a-z]+).)*', 'htmlPattern' => 'foobar', )); $this->assertSame('((?![0-9]$|[a-z]+).)*', $constraint->pattern); $this->assertSame('foobar', $constraint->getHtmlPattern()); } }
isauragalafate/drupal8
vendor/symfony/validator/Tests/Constraints/RegexTest.php
PHP
gpl-2.0
3,009
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Rest\Notify\V1\Service; use Twilio\Options; use Twilio\Values; /** * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. */ abstract class BindingOptions { /** * @param string $tag The tag * @param string $notificationProtocolVersion The notification_protocol_version * @param string $credentialSid The credential_sid * @param string $endpoint The endpoint * @return CreateBindingOptions Options builder */ public static function create($tag = Values::NONE, $notificationProtocolVersion = Values::NONE, $credentialSid = Values::NONE, $endpoint = Values::NONE) { return new CreateBindingOptions($tag, $notificationProtocolVersion, $credentialSid, $endpoint); } /** * @param \DateTime $startDate The start_date * @param \DateTime $endDate The end_date * @param string $identity The identity * @param string $tag The tag * @return ReadBindingOptions Options builder */ public static function read($startDate = Values::NONE, $endDate = Values::NONE, $identity = Values::NONE, $tag = Values::NONE) { return new ReadBindingOptions($startDate, $endDate, $identity, $tag); } } class CreateBindingOptions extends Options { /** * @param string $tag The tag * @param string $notificationProtocolVersion The notification_protocol_version * @param string $credentialSid The credential_sid * @param string $endpoint The endpoint */ public function __construct($tag = Values::NONE, $notificationProtocolVersion = Values::NONE, $credentialSid = Values::NONE, $endpoint = Values::NONE) { $this->options['tag'] = $tag; $this->options['notificationProtocolVersion'] = $notificationProtocolVersion; $this->options['credentialSid'] = $credentialSid; $this->options['endpoint'] = $endpoint; } /** * The tag * * @param string $tag The tag * @return $this Fluent Builder */ public function setTag($tag) { $this->options['tag'] = $tag; return $this; } /** * The notification_protocol_version * * @param string $notificationProtocolVersion The notification_protocol_version * @return $this Fluent Builder */ public function setNotificationProtocolVersion($notificationProtocolVersion) { $this->options['notificationProtocolVersion'] = $notificationProtocolVersion; return $this; } /** * The credential_sid * * @param string $credentialSid The credential_sid * @return $this Fluent Builder */ public function setCredentialSid($credentialSid) { $this->options['credentialSid'] = $credentialSid; return $this; } /** * The endpoint * * @param string $endpoint The endpoint * @return $this Fluent Builder */ public function setEndpoint($endpoint) { $this->options['endpoint'] = $endpoint; return $this; } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { $options = array(); foreach ($this->options as $key => $value) { if ($value != Values::NONE) { $options[] = "$key=$value"; } } return '[Twilio.Notify.V1.CreateBindingOptions ' . implode(' ', $options) . ']'; } } class ReadBindingOptions extends Options { /** * @param \DateTime $startDate The start_date * @param \DateTime $endDate The end_date * @param string $identity The identity * @param string $tag The tag */ public function __construct($startDate = Values::NONE, $endDate = Values::NONE, $identity = Values::NONE, $tag = Values::NONE) { $this->options['startDate'] = $startDate; $this->options['endDate'] = $endDate; $this->options['identity'] = $identity; $this->options['tag'] = $tag; } /** * The start_date * * @param \DateTime $startDate The start_date * @return $this Fluent Builder */ public function setStartDate($startDate) { $this->options['startDate'] = $startDate; return $this; } /** * The end_date * * @param \DateTime $endDate The end_date * @return $this Fluent Builder */ public function setEndDate($endDate) { $this->options['endDate'] = $endDate; return $this; } /** * The identity * * @param string $identity The identity * @return $this Fluent Builder */ public function setIdentity($identity) { $this->options['identity'] = $identity; return $this; } /** * The tag * * @param string $tag The tag * @return $this Fluent Builder */ public function setTag($tag) { $this->options['tag'] = $tag; return $this; } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { $options = array(); foreach ($this->options as $key => $value) { if ($value != Values::NONE) { $options[] = "$key=$value"; } } return '[Twilio.Notify.V1.ReadBindingOptions ' . implode(' ', $options) . ']'; } }
Haynie-Research-and-Development/jarvis
web/webapi/sms/vendor/twilio/sdk/Twilio/Rest/Notify/V1/Service/BindingOptions.php
PHP
gpl-2.0
5,550
<?php namespace Neos\Neos\Controller\Module; /* * This file is part of the Neos.Neos package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; /** * @Flow\Scope("singleton") */ class UserController extends AbstractModuleController { }
aertmann/neos-development-collection
Neos.Neos/Classes/Controller/Module/UserController.php
PHP
gpl-3.0
460
namespace MixERP.Net.WebControls.Flag { public partial class FlagControl { private bool disposed; public override void Dispose() { if (!this.disposed) { this.Dispose(true); base.Dispose(); } } private void Dispose(bool disposing) { if (!disposing) { return; } if (this.container != null) { this.container.Dispose(); this.container = null; } if (this.flagDropDownlist != null) { this.flagDropDownlist.Dispose(); this.flagDropDownlist = null; } if (this.updateButton != null) { this.updateButton.Dispose(); this.updateButton = null; } this.disposed = true; } } }
gguruss/mixerp
src/Libraries/Server Controls/Project/MixERP.Net.WebControls.Flag/FlagControl/IDisposable.cs
C#
gpl-3.0
972
/* * Copyright (C) 2014 Arpit Khurana <arpitkh96@gmail.com> * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.utils; import com.stericson.RootTools.RootTools; import com.stericson.RootTools.execution.Command; import java.io.File; import java.util.ArrayList; public class RootHelper { public static String runAndWait(String cmd,boolean root) { Command c=new Command(0,cmd) { @Override public void commandOutput(int i, String s) { } @Override public void commandTerminated(int i, String s) { } @Override public void commandCompleted(int i, int i2) { } }; try {RootTools.getShell(root).add(c);} catch (Exception e) { // Logger.errorST("Exception when trying to run shell command", e); return null; } if (!waitForCommand(c)) { return null; } return c.toString(); } public static ArrayList<String> runAndWait1(String cmd, final boolean root) { final ArrayList<String> output=new ArrayList<String>(); Command cc=new Command(1,cmd) { @Override public void commandOutput(int i, String s) { output.add(s); // System.out.println("output "+root+s); } @Override public void commandTerminated(int i, String s) { System.out.println("error"+root+s); } @Override public void commandCompleted(int i, int i2) { } }; try { RootTools.getShell(root).add(cc); } catch (Exception e) { // Logger.errorST("Exception when trying to run shell command", e); e.printStackTrace(); return null; } if (!waitForCommand(cc)) { return null; } return output; } private static boolean waitForCommand(Command cmd) { while (!cmd.isFinished()) { synchronized (cmd) { try { if (!cmd.isFinished()) { cmd.wait(2000); } } catch (InterruptedException e) { e.printStackTrace(); } } if (!cmd.isExecuting() && !cmd.isFinished()) { // Logger.errorST("Error: Command is not executing and is not finished!"); return false; } } //Logger.debug("Command Finished!"); return true; } public static String getCommandLineString(String input) { return input.replaceAll(UNIX_ESCAPE_EXPRESSION, "\\\\$1"); } private static final String UNIX_ESCAPE_EXPRESSION = "(\\(|\\)|\\[|\\]|\\s|\'|\"|`|\\{|\\}|&|\\\\|\\?)"; static Futils futils=new Futils(); public static ArrayList<String[]> getFilesList(boolean showSize,String path,boolean showHidden){ File f=new File(path); ArrayList<String[]> files=new ArrayList<String[]>(); try { if(f.exists() && f.isDirectory()){ for(File x:f.listFiles()){ String k="",size=""; if(x.isDirectory()) {k="-1"; if(showSize)size=""+getCount(x); }else if(showSize)size=""+x.length(); if(showHidden){ files.add(new String[]{x.getPath(),"",parseFilePermission(x),k,x.lastModified()+"",size}); } else{if(!x.isHidden()){files.add(new String[]{x.getPath(),"",parseFilePermission(x),k,x.lastModified()+"",size});}} } }}catch (Exception e){} return files;} public static String[] addFile(File x,boolean showSize,boolean showHidden){ String k="",size=""; if(x.isDirectory()) { k="-1"; if(showSize)size=""+getCount(x); }else if(showSize) size=""+x.length(); if(showHidden){ return (new String[]{x.getPath(),"",parseFilePermission(x),k,x.lastModified()+"", size}); } else { if(!x.isHidden()) {return (new String[]{x.getPath(),"",parseFilePermission(x),k,x .lastModified()+"",size}); } } return null; } public static String parseFilePermission(File f){ String per=""; if(f.canRead()){per=per+"r";} if(f.canWrite()){per=per+"w";} if(f.canExecute()){per=per+"x";} return per;} public static ArrayList<String[]> getFilesList(String path,boolean root,boolean showHidden,boolean showSize) { String p = " "; if (showHidden) p = "a "; Futils futils = new Futils(); ArrayList<String[]> a = new ArrayList<String[]>(); ArrayList<String> ls = new ArrayList<String>(); if (root) { if (!path.startsWith("/storage")) { String cpath = getCommandLineString(path); ls = runAndWait1("ls -l" + p + cpath, root); if(ls!=null){ for (String file : ls) { if (!file.contains("Permission denied")) try { String[] array = futils.parseName(file); array[0] = path + "/" + array[0]; a.add(array); } catch (Exception e) { System.out.println(file); e.printStackTrace(); } }} } else if (futils.canListFiles(new File(path))) { a = getFilesList(showSize,path, showHidden); } else { a = new ArrayList<String[]>(); } } else if (futils.canListFiles(new File(path))) { a = getFilesList(showSize,path, showHidden); } else { a = new ArrayList<String[]>(); } if (a.size() == 0 && futils.canListFiles(new File(path))) { a = getFilesList(showSize,path, showHidden); } return a; } public static Integer getCount(File f){ if(f.exists() && f.canRead() && f.isDirectory()){ try{return f.listFiles().length;}catch(Exception e){return 0;} } return null;}}
jiyuren/AmazeFileManager-1
src/main/java/com/amaze/filemanager/utils/RootHelper.java
Java
gpl-3.0
7,137
package aws import ( "fmt" "reflect" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccAWSAutoScalingGroup_basic(t *testing.T) { var group autoscaling.Group var lc autoscaling.LaunchConfiguration resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAWSAutoScalingGroupConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2), testAccCheckAWSAutoScalingGroupAttributes(&group), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "name", "foobar3-terraform-test"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "max_size", "5"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "min_size", "2"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "health_check_grace_period", "300"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "health_check_type", "ELB"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "desired_capacity", "4"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "force_delete", "true"), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "termination_policies.912102603", "OldestInstance"), ), }, resource.TestStep{ Config: testAccAWSAutoScalingGroupConfigUpdate, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.new", &lc), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "desired_capacity", "5"), testLaunchConfigurationName("aws_autoscaling_group.bar", &lc), testAccCheckAutoscalingTags(&group.Tags, "Bar", map[string]interface{}{ "value": "bar-foo", "propagate_at_launch": true, }), ), }, }, }) } func TestAccAWSAutoScalingGroup_tags(t *testing.T) { var group autoscaling.Group resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAWSAutoScalingGroupConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), testAccCheckAutoscalingTags(&group.Tags, "Foo", map[string]interface{}{ "value": "foo-bar", "propagate_at_launch": true, }), ), }, resource.TestStep{ Config: testAccAWSAutoScalingGroupConfigUpdate, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), testAccCheckAutoscalingTagNotExists(&group.Tags, "Foo"), testAccCheckAutoscalingTags(&group.Tags, "Bar", map[string]interface{}{ "value": "bar-foo", "propagate_at_launch": true, }), ), }, }, }) } func TestAccAWSAutoScalingGroup_VpcUpdates(t *testing.T) { var group autoscaling.Group resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAWSAutoScalingGroupConfigWithAZ, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), ), }, resource.TestStep{ Config: testAccAWSAutoScalingGroupConfigWithVPCIdent, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(&group), ), }, }, }) } func TestAccAWSAutoScalingGroup_WithLoadBalancer(t *testing.T) { var group autoscaling.Group resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAWSAutoScalingGroupConfigWithLoadBalancer, Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(&group), ), }, }, }) } func testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).autoscalingconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_autoscaling_group" { continue } // Try to find the Group describeGroups, err := conn.DescribeAutoScalingGroups( &autoscaling.DescribeAutoScalingGroupsInput{ AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)}, }) if err == nil { if len(describeGroups.AutoScalingGroups) != 0 && *describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID { return fmt.Errorf("AutoScaling Group still exists") } } // Verify the error ec2err, ok := err.(awserr.Error) if !ok { return err } if ec2err.Code() != "InvalidGroup.NotFound" { return err } } return nil } func testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.Group) resource.TestCheckFunc { return func(s *terraform.State) error { if *group.AvailabilityZones[0] != "us-west-2a" { return fmt.Errorf("Bad availability_zones: %#v", group.AvailabilityZones[0]) } if *group.AutoScalingGroupName != "foobar3-terraform-test" { return fmt.Errorf("Bad name: %s", *group.AutoScalingGroupName) } if *group.MaxSize != 5 { return fmt.Errorf("Bad max_size: %d", *group.MaxSize) } if *group.MinSize != 2 { return fmt.Errorf("Bad max_size: %d", *group.MinSize) } if *group.HealthCheckType != "ELB" { return fmt.Errorf("Bad health_check_type,\nexpected: %s\ngot: %s", "ELB", *group.HealthCheckType) } if *group.HealthCheckGracePeriod != 300 { return fmt.Errorf("Bad health_check_grace_period: %d", *group.HealthCheckGracePeriod) } if *group.DesiredCapacity != 4 { return fmt.Errorf("Bad desired_capacity: %d", *group.DesiredCapacity) } if *group.LaunchConfigurationName == "" { return fmt.Errorf("Bad launch configuration name: %s", *group.LaunchConfigurationName) } t := &autoscaling.TagDescription{ Key: aws.String("Foo"), Value: aws.String("foo-bar"), PropagateAtLaunch: aws.Bool(true), ResourceType: aws.String("auto-scaling-group"), ResourceID: group.AutoScalingGroupName, } if !reflect.DeepEqual(group.Tags[0], t) { return fmt.Errorf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", group.Tags[0], t) } return nil } } func testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(group *autoscaling.Group) resource.TestCheckFunc { return func(s *terraform.State) error { if *group.LoadBalancerNames[0] != "foobar-terraform-test" { return fmt.Errorf("Bad load_balancers: %#v", group.LoadBalancerNames[0]) } return nil } } func testAccCheckAWSAutoScalingGroupExists(n string, group *autoscaling.Group) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No AutoScaling Group ID is set") } conn := testAccProvider.Meta().(*AWSClient).autoscalingconn describeGroups, err := conn.DescribeAutoScalingGroups( &autoscaling.DescribeAutoScalingGroupsInput{ AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)}, }) if err != nil { return err } if len(describeGroups.AutoScalingGroups) != 1 || *describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID { return fmt.Errorf("AutoScaling Group not found") } *group = *describeGroups.AutoScalingGroups[0] return nil } } func testLaunchConfigurationName(n string, lc *autoscaling.LaunchConfiguration) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if *lc.LaunchConfigurationName != rs.Primary.Attributes["launch_configuration"] { return fmt.Errorf("Launch configuration names do not match") } return nil } } func testAccCheckAWSAutoScalingGroupHealthyCapacity( g *autoscaling.Group, exp int) resource.TestCheckFunc { return func(s *terraform.State) error { healthy := 0 for _, i := range g.Instances { if i.HealthStatus == nil { continue } if strings.EqualFold(*i.HealthStatus, "Healthy") { healthy++ } } if healthy < exp { return fmt.Errorf("Expected at least %d healthy, got %d.", exp, healthy) } return nil } } func testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(group *autoscaling.Group) resource.TestCheckFunc { return func(s *terraform.State) error { // Grab Subnet Ids var subnets []string for _, rs := range s.RootModule().Resources { if rs.Type != "aws_subnet" { continue } subnets = append(subnets, rs.Primary.Attributes["id"]) } if group.VPCZoneIdentifier == nil { return fmt.Errorf("Bad VPC Zone Identifier\nexpected: %s\ngot nil", subnets) } zones := strings.Split(*group.VPCZoneIdentifier, ",") remaining := len(zones) for _, z := range zones { for _, s := range subnets { if z == s { remaining-- } } } if remaining != 0 { return fmt.Errorf("Bad VPC Zone Identifier match\nexpected: %s\ngot:%s", zones, subnets) } return nil } } const testAccAWSAutoScalingGroupConfig = ` resource "aws_launch_configuration" "foobar" { image_id = "ami-21f78e11" instance_type = "t1.micro" } resource "aws_autoscaling_group" "bar" { availability_zones = ["us-west-2a"] name = "foobar3-terraform-test" max_size = 5 min_size = 2 health_check_grace_period = 300 health_check_type = "ELB" desired_capacity = 4 force_delete = true termination_policies = ["OldestInstance"] launch_configuration = "${aws_launch_configuration.foobar.name}" tag { key = "Foo" value = "foo-bar" propagate_at_launch = true } } ` const testAccAWSAutoScalingGroupConfigUpdate = ` resource "aws_launch_configuration" "foobar" { image_id = "ami-21f78e11" instance_type = "t1.micro" } resource "aws_launch_configuration" "new" { image_id = "ami-21f78e11" instance_type = "t1.micro" } resource "aws_autoscaling_group" "bar" { availability_zones = ["us-west-2a"] name = "foobar3-terraform-test" max_size = 5 min_size = 2 health_check_grace_period = 300 health_check_type = "ELB" desired_capacity = 5 force_delete = true launch_configuration = "${aws_launch_configuration.new.name}" tag { key = "Bar" value = "bar-foo" propagate_at_launch = true } } ` const testAccAWSAutoScalingGroupConfigWithLoadBalancer = ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" tags { Name = "tf-asg-test" } } resource "aws_internet_gateway" "gw" { vpc_id = "${aws_vpc.foo.id}" } resource "aws_subnet" "foo" { cidr_block = "10.1.1.0/24" vpc_id = "${aws_vpc.foo.id}" } resource "aws_security_group" "foo" { vpc_id="${aws_vpc.foo.id}" ingress { protocol = "-1" from_port = 0 to_port = 0 cidr_blocks = ["0.0.0.0/0"] } egress { protocol = "-1" from_port = 0 to_port = 0 cidr_blocks = ["0.0.0.0/0"] } } resource "aws_elb" "bar" { name = "foobar-terraform-test" subnets = ["${aws_subnet.foo.id}"] security_groups = ["${aws_security_group.foo.id}"] listener { instance_port = 80 instance_protocol = "http" lb_port = 80 lb_protocol = "http" } health_check { healthy_threshold = 2 unhealthy_threshold = 2 target = "HTTP:80/" interval = 5 timeout = 2 } depends_on = ["aws_internet_gateway.gw"] } resource "aws_launch_configuration" "foobar" { // need an AMI that listens on :80 at boot, this is: // bitnami-nginxstack-1.6.1-0-linux-ubuntu-14.04.1-x86_64-hvm-ebs-ami-99f5b1a9-3 image_id = "ami-b5b3fc85" instance_type = "t2.micro" security_groups = ["${aws_security_group.foo.id}"] } resource "aws_autoscaling_group" "bar" { availability_zones = ["${aws_subnet.foo.availability_zone}"] vpc_zone_identifier = ["${aws_subnet.foo.id}"] name = "foobar3-terraform-test" max_size = 2 min_size = 2 health_check_grace_period = 300 health_check_type = "ELB" min_elb_capacity = 2 force_delete = true launch_configuration = "${aws_launch_configuration.foobar.name}" load_balancers = ["${aws_elb.bar.name}"] } ` const testAccAWSAutoScalingGroupConfigWithAZ = ` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" tags { Name = "terraform-test" } } resource "aws_subnet" "main" { vpc_id = "${aws_vpc.default.id}" cidr_block = "10.0.1.0/24" availability_zone = "us-west-2a" tags { Name = "terraform-test" } } resource "aws_subnet" "alt" { vpc_id = "${aws_vpc.default.id}" cidr_block = "10.0.2.0/24" availability_zone = "us-west-2b" tags { Name = "asg-vpc-thing" } } resource "aws_launch_configuration" "foobar" { name = "vpc-asg-test" image_id = "ami-b5b3fc85" instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { availability_zones = ["us-west-2a"] name = "vpc-asg-test" max_size = 2 min_size = 1 health_check_grace_period = 300 health_check_type = "ELB" desired_capacity = 1 force_delete = true termination_policies = ["OldestInstance"] launch_configuration = "${aws_launch_configuration.foobar.name}" } ` const testAccAWSAutoScalingGroupConfigWithVPCIdent = ` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" tags { Name = "terraform-test" } } resource "aws_subnet" "main" { vpc_id = "${aws_vpc.default.id}" cidr_block = "10.0.1.0/24" availability_zone = "us-west-2a" tags { Name = "terraform-test" } } resource "aws_subnet" "alt" { vpc_id = "${aws_vpc.default.id}" cidr_block = "10.0.2.0/24" availability_zone = "us-west-2b" tags { Name = "asg-vpc-thing" } } resource "aws_launch_configuration" "foobar" { name = "vpc-asg-test" image_id = "ami-b5b3fc85" instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { vpc_zone_identifier = [ "${aws_subnet.main.id}", "${aws_subnet.alt.id}", ] name = "vpc-asg-test" max_size = 2 min_size = 1 health_check_grace_period = 300 health_check_type = "ELB" desired_capacity = 1 force_delete = true termination_policies = ["OldestInstance"] launch_configuration = "${aws_launch_configuration.foobar.name}" } `
keen99/terraform
builtin/providers/aws/resource_aws_autoscaling_group_test.go
GO
mpl-2.0
15,294
/* * eXist Open Source Native XML Database * Copyright (C) 2009-2011 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.debuggee.dbgp.packets; import org.apache.mina.core.session.IoSession; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class StepInto extends AbstractCommandContinuation { public StepInto(IoSession session, String args) { super(session, args); } /* (non-Javadoc) * @see org.exist.debuggee.dgbp.packets.Command#exec() */ @Override public synchronized void exec() { getJoint().continuation(this); } public synchronized byte[] responseBytes() { String responce = xml_declaration + "<response " + namespaces + "command=\"step_into\" " + "status=\""+getStatus()+"\" " + "reason=\"ok\" " + "transaction_id=\""+transactionID+"\"/>"; return responce.getBytes(); } public byte[] commandBytes() { String command = "step_into -i "+transactionID; return command.getBytes(); } public int getType() { return STEP_INTO; } public boolean is(int type) { return (type == STEP_INTO); } public String toString() { return "step_into ["+transactionID+"]"; } }
MjAbuz/exist
extensions/debuggee/src/org/exist/debuggee/dbgp/packets/StepInto.java
Java
lgpl-2.1
1,942
package bootstrappolicy import ( rbacrest "k8s.io/kubernetes/pkg/registry/rbac/rest" ) func Policy() *rbacrest.PolicyData { return &rbacrest.PolicyData{ ClusterRoles: GetBootstrapClusterRoles(), ClusterRoleBindings: GetBootstrapClusterRoleBindings(), Roles: GetBootstrapNamespaceRoles(), RoleBindings: GetBootstrapNamespaceRoleBindings(), } }
kedgeproject/kedge
vendor/github.com/openshift/origin/pkg/cmd/server/bootstrappolicy/all.go
GO
apache-2.0
384
package com.codahale.metrics.health.jvm; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.jvm.ThreadDeadlockDetector; import java.util.Set; /** * A health check which returns healthy if no threads are deadlocked. */ public class ThreadDeadlockHealthCheck extends HealthCheck { private final ThreadDeadlockDetector detector; /** * Creates a new health check. */ public ThreadDeadlockHealthCheck() { this(new ThreadDeadlockDetector()); } /** * Creates a new health check with the given detector. * * @param detector a thread deadlock detector */ public ThreadDeadlockHealthCheck(ThreadDeadlockDetector detector) { this.detector = detector; } @Override protected Result check() throws Exception { final Set<String> threads = detector.getDeadlockedThreads(); if (threads.isEmpty()) { return Result.healthy(); } return Result.unhealthy(threads.toString()); } }
gburton1/metrics
metrics-healthchecks/src/main/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheck.java
Java
apache-2.0
1,021
package io.dropwizard.jdbi.args; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.time.Instant; import java.util.Calendar; import java.util.Optional; /** * An {@link Argument} for {@link Instant} objects. */ public class InstantArgument implements Argument { private final Instant instant; private final Optional<Calendar> calendar; protected InstantArgument(final Instant instant, final Optional<Calendar> calendar) { this.instant = instant; this.calendar = calendar; } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { if (instant != null) { if (calendar.isPresent()) { // We need to make a clone, because Calendar is not thread-safe // and some JDBC drivers mutate it during time calculations final Calendar calendarClone = (Calendar) calendar.get().clone(); statement.setTimestamp(position, Timestamp.from(instant), calendarClone); } else { statement.setTimestamp(position, Timestamp.from(instant)); } } else { statement.setNull(position, Types.TIMESTAMP); } } }
patrox/dropwizard
dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/args/InstantArgument.java
Java
apache-2.0
1,397
package cache import ( "time" kapi "k8s.io/kubernetes/pkg/api" errors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" authorizationapi "github.com/openshift/origin/pkg/authorization/api" "github.com/openshift/origin/pkg/authorization/client" clusterbindingregistry "github.com/openshift/origin/pkg/authorization/registry/clusterpolicybinding" ) type readOnlyClusterPolicyBindingCache struct { registry clusterbindingregistry.WatchingRegistry indexer cache.Indexer reflector *cache.Reflector keyFunc cache.KeyFunc } func NewReadOnlyClusterPolicyBindingCache(registry clusterbindingregistry.WatchingRegistry) *readOnlyClusterPolicyBindingCache { ctx := kapi.WithNamespace(kapi.NewContext(), kapi.NamespaceAll) indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc}) reflector := cache.NewReflector( &cache.ListWatch{ ListFunc: func() (runtime.Object, error) { return registry.ListClusterPolicyBindings(ctx, labels.Everything(), fields.Everything()) }, WatchFunc: func(resourceVersion string) (watch.Interface, error) { return registry.WatchClusterPolicyBindings(ctx, labels.Everything(), fields.Everything(), resourceVersion) }, }, &authorizationapi.ClusterPolicyBinding{}, indexer, 2*time.Minute, ) return &readOnlyClusterPolicyBindingCache{ registry: registry, indexer: indexer, reflector: reflector, keyFunc: cache.MetaNamespaceKeyFunc, } } // Run begins watching and synchronizing the cache func (c *readOnlyClusterPolicyBindingCache) Run() { c.reflector.Run() } // RunUntil starts a watch and handles watch events. Will restart the watch if it is closed. // RunUntil starts a goroutine and returns immediately. It will exit when stopCh is closed. func (c *readOnlyClusterPolicyBindingCache) RunUntil(stopChannel <-chan struct{}) { c.reflector.RunUntil(stopChannel) } // LastSyncResourceVersion exposes the LastSyncResourceVersion of the internal reflector func (c *readOnlyClusterPolicyBindingCache) LastSyncResourceVersion() string { return c.reflector.LastSyncResourceVersion() } func (c *readOnlyClusterPolicyBindingCache) List(label labels.Selector, field fields.Selector) (*authorizationapi.ClusterPolicyBindingList, error) { clusterPolicyBindingList := &authorizationapi.ClusterPolicyBindingList{} returnedList := c.indexer.List() for i := range returnedList { clusterPolicyBinding, castOK := returnedList[i].(*authorizationapi.ClusterPolicyBinding) if !castOK { return clusterPolicyBindingList, errors.NewInvalid("ClusterPolicyBinding", "clusterPolicyBinding", []error{}) } if label.Matches(labels.Set(clusterPolicyBinding.Labels)) && field.Matches(authorizationapi.ClusterPolicyBindingToSelectableFields(clusterPolicyBinding)) { clusterPolicyBindingList.Items = append(clusterPolicyBindingList.Items, *clusterPolicyBinding) } } return clusterPolicyBindingList, nil } func (c *readOnlyClusterPolicyBindingCache) Get(name string) (*authorizationapi.ClusterPolicyBinding, error) { keyObj := &authorizationapi.ClusterPolicyBinding{ObjectMeta: kapi.ObjectMeta{Name: name}} key, _ := c.keyFunc(keyObj) item, exists, getErr := c.indexer.GetByKey(key) if getErr != nil { return &authorizationapi.ClusterPolicyBinding{}, getErr } if !exists { existsErr := errors.NewNotFound("ClusterPolicyBinding", name) return &authorizationapi.ClusterPolicyBinding{}, existsErr } clusterPolicyBinding, castOK := item.(*authorizationapi.ClusterPolicyBinding) if !castOK { castErr := errors.NewInvalid("ClusterPolicyBinding", name, []error{}) return &authorizationapi.ClusterPolicyBinding{}, castErr } return clusterPolicyBinding, nil } func newReadOnlyClusterPolicyBindings(cache readOnlyAuthorizationCache) client.ReadOnlyClusterPolicyBindingInterface { return cache.readOnlyClusterPolicyBindingCache }
yepengxj/df_st_origin1
pkg/authorization/cache/clusterpolicybinding.go
GO
apache-2.0
4,026
//// [tests/cases/compiler/pathMappingBasedModuleResolution5_classic.ts] //// //// [file1.ts] import {x} from "folder2/file1" import {y} from "folder3/file2" import {z} from "components/file3" import {z1} from "file4" declare function use(a: any): void; use(x.toExponential()); use(y.toExponential()); use(z.toExponential()); use(z1.toExponential()); //// [file1.ts] export var x = 1; //// [file2.ts] export var y = 1; //// [file3.ts] export var z = 1; //// [file4.ts] export var z1 = 1; //// [file1.js] define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.x = 1; }); //// [file2.js] define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.y = 1; }); //// [file3.js] define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.z = 1; }); //// [file4.js] define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.z1 = 1; }); //// [file1.js] define(["require", "exports", "folder2/file1", "folder3/file2", "components/file3", "file4"], function (require, exports, file1_1, file2_1, file3_1, file4_1) { "use strict"; exports.__esModule = true; use(file1_1.x.toExponential()); use(file2_1.y.toExponential()); use(file3_1.z.toExponential()); use(file4_1.z1.toExponential()); });
weswigham/TypeScript
tests/baselines/reference/pathMappingBasedModuleResolution5_classic.js
JavaScript
apache-2.0
1,513
/* * 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.jclouds.aws.ec2.features; import static org.jclouds.aws.reference.FormParameters.ACTION; import java.util.Set; import javax.inject.Named; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404; import org.jclouds.aws.ec2.domain.AWSRunningInstance; import org.jclouds.aws.ec2.xml.AWSDescribeInstancesResponseHandler; import org.jclouds.aws.ec2.xml.AWSRunInstancesResponseHandler; import org.jclouds.aws.filters.FormSigner; import org.jclouds.ec2.binders.BindFiltersToIndexedFormParams; import org.jclouds.ec2.binders.BindInstanceIdsToIndexedFormParams; import org.jclouds.ec2.binders.IfNotNullBindAvailabilityZoneToFormParam; import org.jclouds.ec2.domain.Reservation; import org.jclouds.ec2.features.InstanceApi; import org.jclouds.ec2.options.RunInstancesOptions; import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.EndpointParam; import org.jclouds.rest.annotations.Fallback; import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; import com.google.common.collect.Multimap; /** * Provides access to EC2 Instance Services via their REST API. * <p/> */ @RequestFilters(FormSigner.class) @VirtualHost public interface AWSInstanceApi extends InstanceApi { @Named("DescribeInstances") @Override @POST @Path("/") @FormParams(keys = ACTION, values = "DescribeInstances") @XMLResponseParser(AWSDescribeInstancesResponseHandler.class) @Fallback(EmptySetOnNotFoundOr404.class) Set<? extends Reservation<? extends AWSRunningInstance>> describeInstancesInRegion( @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds); @Named("DescribeInstances") @POST @Path("/") @FormParams(keys = ACTION, values = "DescribeInstances") @XMLResponseParser(AWSDescribeInstancesResponseHandler.class) @Fallback(EmptySetOnNotFoundOr404.class) Set<? extends Reservation<? extends AWSRunningInstance>> describeInstancesInRegionWithFilter( @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter); @Named("RunInstances") @Override @POST @Path("/") @FormParams(keys = ACTION, values = "RunInstances") @XMLResponseParser(AWSRunInstancesResponseHandler.class) Reservation<? extends AWSRunningInstance> runInstancesInRegion( @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @Nullable @BinderParam(IfNotNullBindAvailabilityZoneToFormParam.class) String nullableAvailabilityZone, @FormParam("ImageId") String imageId, @FormParam("MinCount") int minCount, @FormParam("MaxCount") int maxCount, RunInstancesOptions... options); }
yanzhijun/jclouds-aliyun
providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/AWSInstanceApi.java
Java
apache-2.0
4,022
/* * 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.ignite.internal.direct; import java.nio.ByteBuffer; import java.util.BitSet; import java.util.Collection; import java.util.Map; import java.util.UUID; import org.apache.ignite.internal.direct.state.DirectMessageState; import org.apache.ignite.internal.direct.state.DirectMessageStateItem; import org.apache.ignite.internal.direct.stream.DirectByteBufferStream; import org.apache.ignite.internal.direct.stream.v1.DirectByteBufferStreamImplV1; import org.apache.ignite.internal.direct.stream.v2.DirectByteBufferStreamImplV2; import org.apache.ignite.internal.direct.stream.v3.DirectByteBufferStreamImplV3; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.util.tostring.GridToStringInclude; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.lang.IgniteOutClosure; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.plugin.extensions.communication.Message; import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType; import org.apache.ignite.plugin.extensions.communication.MessageWriter; import org.jetbrains.annotations.Nullable; /** * Message writer implementation. */ public class DirectMessageWriter implements MessageWriter { /** State. */ @GridToStringInclude private final DirectMessageState<StateItem> state; /** Protocol version. */ @GridToStringInclude private final byte protoVer; /** * @param protoVer Protocol version. */ public DirectMessageWriter(final byte protoVer) { state = new DirectMessageState<>(StateItem.class, new IgniteOutClosure<StateItem>() { @Override public StateItem apply() { return new StateItem(protoVer); } }); this.protoVer = protoVer; } /** {@inheritDoc} */ @Override public void setBuffer(ByteBuffer buf) { state.item().stream.setBuffer(buf); } /** {@inheritDoc} */ @Override public void setCurrentWriteClass(Class<? extends Message> msgCls) { // No-op. } /** {@inheritDoc} */ @Override public boolean writeHeader(short type, byte fieldCnt) { DirectByteBufferStream stream = state.item().stream; stream.writeShort(type); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeByte(String name, byte val) { DirectByteBufferStream stream = state.item().stream; stream.writeByte(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeShort(String name, short val) { DirectByteBufferStream stream = state.item().stream; stream.writeShort(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeInt(String name, int val) { DirectByteBufferStream stream = state.item().stream; stream.writeInt(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeLong(String name, long val) { DirectByteBufferStream stream = state.item().stream; stream.writeLong(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeFloat(String name, float val) { DirectByteBufferStream stream = state.item().stream; stream.writeFloat(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeDouble(String name, double val) { DirectByteBufferStream stream = state.item().stream; stream.writeDouble(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeChar(String name, char val) { DirectByteBufferStream stream = state.item().stream; stream.writeChar(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeBoolean(String name, boolean val) { DirectByteBufferStream stream = state.item().stream; stream.writeBoolean(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeByteArray(String name, @Nullable byte[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeByteArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeByteArray(String name, byte[] val, long off, int len) { DirectByteBufferStream stream = state.item().stream; stream.writeByteArray(val, off, len); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeShortArray(String name, @Nullable short[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeShortArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeIntArray(String name, @Nullable int[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeIntArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeLongArray(String name, @Nullable long[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeLongArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeLongArray(String name, long[] val, int len) { DirectByteBufferStream stream = state.item().stream; stream.writeLongArray(val, len); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeFloatArray(String name, @Nullable float[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeFloatArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeDoubleArray(String name, @Nullable double[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeDoubleArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeCharArray(String name, @Nullable char[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeCharArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeBooleanArray(String name, @Nullable boolean[] val) { DirectByteBufferStream stream = state.item().stream; stream.writeBooleanArray(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeString(String name, String val) { DirectByteBufferStream stream = state.item().stream; stream.writeString(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeBitSet(String name, BitSet val) { DirectByteBufferStream stream = state.item().stream; stream.writeBitSet(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeUuid(String name, UUID val) { DirectByteBufferStream stream = state.item().stream; stream.writeUuid(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeIgniteUuid(String name, IgniteUuid val) { DirectByteBufferStream stream = state.item().stream; stream.writeIgniteUuid(val); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean writeAffinityTopologyVersion(String name, AffinityTopologyVersion val) { if (protoVer >= 3) { DirectByteBufferStream stream = state.item().stream; stream.writeAffinityTopologyVersion(val); return stream.lastFinished(); } return writeMessage(name, val); } /** {@inheritDoc} */ @Override public boolean writeMessage(String name, @Nullable Message msg) { DirectByteBufferStream stream = state.item().stream; stream.writeMessage(msg, this); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public <T> boolean writeObjectArray(String name, T[] arr, MessageCollectionItemType itemType) { DirectByteBufferStream stream = state.item().stream; stream.writeObjectArray(arr, itemType, this); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public <T> boolean writeCollection(String name, Collection<T> col, MessageCollectionItemType itemType) { DirectByteBufferStream stream = state.item().stream; stream.writeCollection(col, itemType, this); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public <K, V> boolean writeMap(String name, Map<K, V> map, MessageCollectionItemType keyType, MessageCollectionItemType valType) { DirectByteBufferStream stream = state.item().stream; stream.writeMap(map, keyType, valType, this); return stream.lastFinished(); } /** {@inheritDoc} */ @Override public boolean isHeaderWritten() { return state.item().hdrWritten; } /** {@inheritDoc} */ @Override public void onHeaderWritten() { state.item().hdrWritten = true; } /** {@inheritDoc} */ @Override public int state() { return state.item().state; } /** {@inheritDoc} */ @Override public void incrementState() { state.item().state++; } /** {@inheritDoc} */ @Override public void beforeInnerMessageWrite() { state.forward(); } /** {@inheritDoc} */ @Override public void afterInnerMessageWrite(boolean finished) { state.backward(finished); } /** {@inheritDoc} */ @Override public void reset() { state.reset(); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(DirectMessageWriter.class, this); } /** */ private static class StateItem implements DirectMessageStateItem { /** */ private final DirectByteBufferStream stream; /** */ private int state; /** */ private boolean hdrWritten; /** * @param protoVer Protocol version. */ public StateItem(byte protoVer) { switch (protoVer) { case 1: stream = new DirectByteBufferStreamImplV1(null); break; case 2: stream = new DirectByteBufferStreamImplV2(null); break; case 3: stream = new DirectByteBufferStreamImplV3(null); break; default: throw new IllegalStateException("Invalid protocol version: " + protoVer); } } /** {@inheritDoc} */ @Override public void reset() { state = 0; hdrWritten = false; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(StateItem.class, this); } } }
BiryukovVA/ignite
modules/core/src/main/java/org/apache/ignite/internal/direct/DirectMessageWriter.java
Java
apache-2.0
12,148
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define(factory) : (factory()); }(this, (function () { 'use strict'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ Zone.__load_patch('bluebird', function (global, Zone) { // TODO: @JiaLiPassion, we can automatically patch bluebird // if global.Promise = Bluebird, but sometimes in nodejs, // global.Promise is not Bluebird, and Bluebird is just be // used by other libraries such as sequelize, so I think it is // safe to just expose a method to patch Bluebird explicitly var BLUEBIRD = 'bluebird'; Zone[Zone.__symbol__(BLUEBIRD)] = function patchBluebird(Bluebird) { Bluebird.setScheduler(function (fn) { Zone.current.scheduleMicroTask(BLUEBIRD, fn); }); }; }); })));
Geovanny0401/bookStore
bookstore-front/node_modules/zone.js/dist/zone-bluebird.js
JavaScript
apache-2.0
1,237
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.testIntegration; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.psi.codeStyle.NameUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class TestFinderHelper { public static PsiElement findSourceElement(@NotNull final PsiElement from) { for (TestFinder each : getFinders()) { PsiElement result = each.findSourceElement(from); if (result != null) return result; } return null; } public static Collection<PsiElement> findTestsForClass(@NotNull final PsiElement element) { Collection<PsiElement> result = new LinkedHashSet<>(); for (TestFinder each : getFinders()) { result.addAll(each.findTestsForClass(element)); } return result; } public static Collection<PsiElement> findClassesForTest(@NotNull final PsiElement element) { Collection<PsiElement> result = new LinkedHashSet<>(); for (TestFinder each : getFinders()) { result.addAll(each.findClassesForTest(element)); } return result; } public static boolean isTest(PsiElement element) { if (element == null) return false; for (TestFinder each : getFinders()) { if (each.isTest(element)) return true; } return false; } public static TestFinder[] getFinders() { return Extensions.getExtensions(TestFinder.EP_NAME); } public static Integer calcTestNameProximity(final String className, final String testName) { int posProximity = testName.indexOf(className); int sizeProximity = testName.length() - className.length(); return posProximity + sizeProximity; } public static List<PsiElement> getSortedElements(final List<Pair<? extends PsiNamedElement, Integer>> elementsWithWeights, final boolean weightsAscending) { return getSortedElements(elementsWithWeights, weightsAscending, null); } public static List<PsiElement> getSortedElements(final List<Pair<? extends PsiNamedElement, Integer>> elementsWithWeights, final boolean weightsAscending, @Nullable final Comparator<PsiElement> sameNameComparator) { Collections.sort(elementsWithWeights, (o1, o2) -> { int result = weightsAscending ? o1.second.compareTo(o2.second) : o2.second.compareTo(o1.second); if (result == 0) result = Comparing.compare(o1.first.getName(), o2.first.getName()); if (result == 0 && sameNameComparator != null) result = sameNameComparator.compare(o1.first, o2.first); return result; }); final List<PsiElement> result = new ArrayList<>(elementsWithWeights.size()); for (Pair<? extends PsiNamedElement, Integer> each : elementsWithWeights) { result.add(each.first); } return result; } public static List<Pair<String, Integer>> collectPossibleClassNamesWithWeights(String testName) { String[] words = NameUtil.splitNameIntoWords(testName); List<Pair<String, Integer>> result = new ArrayList<>(); for (int from = 0; from < words.length; from++) { for (int to = from; to < words.length; to++) { result.add(new Pair<>(StringUtil.join(words, from, to + 1, ""), words.length - from + to)); } } return result; } }
asedunov/intellij-community
platform/lang-impl/src/com/intellij/testIntegration/TestFinderHelper.java
Java
apache-2.0
4,188
<?php namespace SleepingOwl\Admin; use SleepingOwl\Html\FormBuilder; use SleepingOwl\Html\HtmlBuilder; use SleepingOwl\Admin\Menu\MenuItem; use SleepingOwl\Admin\Models\ModelItem; use SleepingOwl\Admin\Models\Models; use Illuminate\Config\Repository; use Illuminate\Filesystem\Filesystem; use Illuminate\Routing\Router as IlluminateRouter; use Symfony\Component\Finder\Finder; use Illuminate\Routing\UrlGenerator; /** * Class Admin * * @package SleepingOwl\Admin */ class Admin { /** * Bootstrap filename */ const BOOTSRAP_FILE = 'bootstrap.php'; /** * @var Admin */ public static $instance; /** * @var string */ public $title; /** * @var Router */ public $router; /** * @var MenuItem */ public $menu; /** * @var Models */ public $models; /** * @var HtmlBuilder */ public $htmlBuilder; /** * @var FormBuilder */ public $formBuilder; /** * @var Finder */ protected $finder; /** * @var string */ protected $bootstrapDirectory; /** * @var Filesystem */ protected $filesystem; /** * @param HtmlBuilder $htmlBuilder * @param FormBuilder $formBuilder * @param Finder $finder * @param Repository $config * @param IlluminateRouter $illuminateRouter * @param UrlGenerator $urlGenerator * @param Filesystem $filesystem */ function __construct(HtmlBuilder $htmlBuilder, FormBuilder $formBuilder, Finder $finder, Repository $config, IlluminateRouter $illuminateRouter, UrlGenerator $urlGenerator, Filesystem $filesystem) { static::$instance = $this; $this->htmlBuilder = $htmlBuilder; $this->formBuilder = $formBuilder; $this->finder = $finder; $this->filesystem = $filesystem; $this->title = $config->get('admin.title'); $this->bootstrapDirectory = $config->get('admin.bootstrapDirectory'); $this->router = new Router($illuminateRouter, $config, $urlGenerator, $config->get('admin.prefix')); $this->menu = new MenuItem; $this->models = new Models; $this->requireBootstrap(); } /** * @return Admin */ public static function instance() { if (is_null(static::$instance)) { app('\SleepingOwl\Admin\Admin'); } return static::$instance; } /** * */ protected function requireBootstrap() { if (! $this->filesystem->isDirectory($this->bootstrapDirectory)) return; $files = $this->finder->create()->files()->name('/^[^_].+\.php$/')->in($this->bootstrapDirectory); $files->sort(function ($a) { return $a->getFilename() !== static::BOOTSRAP_FILE; }); foreach ($files as $file) { $this->filesystem->requireOnce($file); } } /** * @param $class * @return ModelItem */ public static function model($class) { $modelItem = new ModelItem($class); return $modelItem; } /** * @param null $model * @return MenuItem */ public static function menu($model = null) { return new MenuItem($model); } /** * @param string $content * @param $title * @return string */ public static function view($content, $title = null) { $controller = \App::make('SleepingOwl\Admin\Controllers\AdminController', ['disableFilters' => true]); return $controller->renderCustomContent($title, $content); } }
dungbq89/lnews
vendor/sleeping-owl/admin/src/SleepingOwl/Admin/Admin.php
PHP
apache-2.0
3,169
Puppet::Type.newtype(:ec2_scalingpolicy) do @doc = 'Type representing an EC2 scaling policy.' ensurable newparam(:name, namevar: true) do desc 'The name of the scaling policy.' validate do |value| fail 'Scaling policies must have a name' if value == '' fail 'name should be a String' unless value.is_a?(String) end end newproperty(:scaling_adjustment) do desc 'The amount to adjust the size of the group by.' validate do |value| fail 'scaling adjustment cannot be blank' if value == '' end munge do |value| value.to_i end end newproperty(:region) do desc 'The region in which to launch the policy.' validate do |value| fail 'region should not contain spaces' if value =~ /\s/ fail 'region should not be blank' if value == '' fail 'region should be a String' unless value.is_a?(String) end end newproperty(:adjustment_type) do desc 'The type of policy.' validate do |value| fail 'adjustment_type should not contain spaces' if value =~ /\s/ fail 'adjustment_type should not be blank' if value == '' fail 'adjustment_type should be a String' unless value.is_a?(String) end end newproperty(:auto_scaling_group) do desc 'The auto scaling group to attach the policy to.' validate do |value| fail 'auto_scaling_group cannot be blank' if value == '' fail 'auto_scaling_group should be a String' unless value.is_a?(String) end end autorequire(:ec2_autoscalinggroup) do self[:auto_scaling_group] end end
MarsuperMammal/pw_gce
lib/puppet/type/ec2_scalingpolicy.rb
Ruby
apache-2.0
1,573
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.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. */ package com.linkedin.pinot.core.realtime; public class RealtimeIntegrationTest { public void endToEndTest(){ //start zk server //setup cluster //setup realtime resource //start controller //start participants } }
pinotlytics/pinot
pinot-core/src/test/java/com/linkedin/pinot/core/realtime/RealtimeIntegrationTest.java
Java
apache-2.0
877
/* * 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.ignite.internal.processors.query.oom; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Test suite for queries produces OOME in some cases. */ @RunWith(Suite.class) @Suite.SuiteClasses({ //Query history. QueryOOMWithoutQueryParallelismTest.class, QueryOOMWithQueryParallelismTest.class, }) public class IgniteQueryOOMTestSuite { }
NSAmelchev/ignite
modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/oom/IgniteQueryOOMTestSuite.java
Java
apache-2.0
1,192